javascript字符串替换

stringObject.replace(findstring,newstring)

The replace() method returns the string that results when you replace text matching its first argument (a regular expression) with the text of the second argument (a string). If the g (global) flag is not set in the regular expression declaration, this method replaces only the first occurrence of the pattern.

参数说明
findstring 目标字符串
Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag
必选项。指定所要替换的字符串。要执行多次匹配需要添加一个”g“标记。要指定模糊匹配需要添加一个”i“标记

newstring 新字符串
Required. Specifies the string to replace the found value from findstring
必选项。指定所要替换的字符串的新值

全部替换可参考如下实现:

1
var testStr = "aaabbbcccdddaaa";
alert(testStr.replace(/a/g,'x'));
将字符串testStr中的所有a全部替换成x

2
stringObj.replace(new RegExp(oldString,"gm"),newString))
说明:
gm的g表示global, m表示multiLine,可以实现替换全部指定字串。

3
var testStr = "aaabbbcccdddaaa";
str=str.split("a").join("x");
alert(str) ;
将字符串testStr中的所有a多替换成x

参考文档:http://wangyi878750.blog.sohu.com/31370032.html

此条目发表在sitebuild分类目录,贴了, , , 标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据