javascript中使用replaceAll()函数实现字符替换的方法_javascript技巧
程序员文章站
2022-04-11 09:35:51
...
而str.replace(/\-/g,"!")则可以全部替换掉匹配的字符(g为全局标志)。
replace()
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. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./, "!" ); // replace first period with an exclamation pointalert(s);
produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./g, "!" ); // replace all periods with exclamation pointsalert(s);
yields this result: “Hello! Regexps are fun!”
所以可以用以下几种方式.:
string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);
string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。
replace()
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. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./, "!" ); // replace first period with an exclamation pointalert(s);
produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./g, "!" ); // replace all periods with exclamation pointsalert(s);
yields this result: “Hello! Regexps are fun!”
所以可以用以下几种方式.:
string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);
string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。
复制代码 代码如下:
推荐阅读
-
JavaScript正则表达式替换字符串中图片地址(img src)的方法
-
使用JavaScript实现node.js中的path.join方法
-
Javascript中字符串相关常用的使用方法总结
-
在JavaScript中处理字符串之link()方法的使用
-
javascript实现根据函数名称字符串动态执行函数的方法示例
-
javascript中使用正则表达式实现删除字符串中的前后空格
-
JavaScript:17-正则表达式、正则表达式概述、正则表达式在js中的使用、正则表达式中特殊字符、表单验证、正则替换replace
-
JavaScript实现替换字符串中最后一个字符的方法
-
详解JavaScript中数组和字符串的lastIndexOf()方法使用
-
使用JavaScript实现node.js中的path.join方法