javascript的 replace() 方法的使用讲解
2016-05-05 10:43
696 查看
String.prototype.replace()
The [code]replace()method returns a new string with some or all matches of a
patternreplaced by a
replacement.
The
patterncan be a string or a
RegExp, and the
replacementcan be a string or a function to be called for each match.
语法:
str.replace(regexp|substr, newSubStr|function[, flags])
[/code]
Parameters
regexp (pattern)A
RegExpobject or literal. The match is replaced by the return value of parameter #2.
substr (pattern)A
Stringthat is to be replaced by
newSubStr. It is treated as a verbatim string and is notinterpreted as a regular expression.
newSubStr (replacement)The
Stringthat replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
function (replacement)A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.例子:例1:
var str = 'Twas the night before Xmas...'; var newstr = str.replace(/xmas/i, 'Christmas'); console.log(newstr); // Twas the night before Christmas...
例2:
var re = /apples/gi; var str = 'Apples are round, and apples are juicy.'; var newstr = str.replace(re, 'oranges'); console.log(newstr); // oranges are round, and oranges are juicy.
例3:
var re = /(\w+)\s(\w+)/; var str = 'John Smith'; var newstr = str.replace(re, '$2, $1'); console.log(newstr); // Smith, Joh
例4:
function styleHyphenFormat(propertyName) { function upperToHyphenLower(match) { return '-' + match.toLowerCase(); } return propertyName.replace(/[A-Z]/g, upperToHyphenLower); }
例5:
function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics console.log(arguments); return [p1, p2, p3].join(' - '); } var newString = 'abc12345#$*%aaa'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
相关文章推荐
- JavaScript实现返回上一页面并刷新的小例子
- 最近改js学到的一些心得
- JavaScript学习总结(九)——Javascript面向(基于)对象编程
- JavaScript学习总结(八)——JavaScript数组
- JavaScript学习总结(七)——JavaScript函数(function)
- JavaScript学习总结(六)——JavaScript判断数据类型总结
- JavaScript学习总结(五)——Javascript中==和===的区别
- JavaScript跨域总结与解决办法
- JavaScript学习总结(四)——逻辑OR运算符详解
- javascript对象属性为空的判断
- jsm使用
- JS数组方法汇总
- fiddler 挂载 JS文件
- UMeditor图片上传失败之jsp与.NET版本(转载+原创)
- Andorid Json解析大全
- js对联广告代码,兼容性高
- JSP不加载缓存
- 使用Gson解析复杂的json数据
- JavaScript-----判断Caps Lock是否开启
- js中正则表达式