Js 替换一个多行文本的关键字
正常,没有变量的时候应该是这样:
var string = aaabbbcccc;
//把 a 替换成 b:
string.replace("a","b");
以上只能替换第一个匹配的,要全文匹配应该用正则表达式:
string.replace(/a/g,"b");
//正则加个参数 g ,表示全文匹配。
但现在,我要替换的不是 a 这个字符了,而是从外面传进来的一个变量:
var key;
我可以这么写:
string.replace(key,"b");
这只能替换第一个匹配的,要全文匹配就遇到难题了:
string.replace(/key/g,"b");
这样写是不行的,但是变量 key 并传不到正则里面去。
后来我想到了用加号拼接变量,但是也失败了。我无意中发现 java 有个 replaceAll() 方法,我想如果可以这样不就好了吗:
string.replaceAll(key,"b");
这样就不用正则了,变量就能进去了,然后发现 JS 里没有 replaceAll() 这个方法。但是后来发现官方文档中有对这个函数的介绍:
定义和用法 replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
语法:
stringObject.replace(regexp/substr,replacement):regexp/substr
描述:必需。规定子字符串或要替换的模式的 RegExp 对象。
请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。参数:replacement
描述:必需。一个字符串值。规定了替换文本或生成替换文本的函数。
这里,利用 JS 的 RegExp 对象,将 g 参数单拿了出来,同时,正则的内容可以用变量来代替了!!!
string.replace(new RegExp(key,'g'),"b");
更多实例:
例子 1
在本例中,我们将使用 “W3School” 替换字符串中的 “Microsoft”:
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
</script>
//输出:
Visit W3School!
例子 2
在本例中,我们将执行一次全局替换,每当 “Microsoft” 被找到,它就被替换为 “W3School”:
<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
</script>
//输出:
Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.
例子 3
您可以使用本例提供的代码来确保匹配字符串大写字符的正确:
text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");
例子 4
在本例中,我们将把 “Doe, John” 转换为 “John Doe” 的形式:
name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");
例子 5
在本例中,我们将把所有的花引号替换为直引号:
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");
例子 6
在本例中,我们将把字符串中所有单词的首字母都转换为大写:
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);