replace() 替换

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串

var str ='abcdefg';
var n =str.replace(/b/, "2");
console.log(n);

输出结果 a2cdefg

全局替换

var str="Welcome to Microsoft! "
str=str +'\n'+ "We are proud to announce that Microsoft has "
str=str +'\n'+ "one of the largest Web Developers sites in the world."
var n =str.replace(/Microsoft/g, "ITeye");
console.log(n);

 输出结果

Welcome to ITeye!
We are proud to announce that ITeye has
one of the largest Web Developers sites in the world.

将字符串中所有单词的首字母都转换为大写

var str = 'hello world';
str = str.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);

 输出结果"Hello World"

将'world, hello'变为'hello world'

n = "World, Hello";
n.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");

 逗号后面有空格

猜你喜欢

转载自1175644344.iteye.com/blog/2301628