JavaScript的replace() 使用方法&&怎么替换全部

记录下js中经常用到的replace()替换

一、官方定义

str.replace(regexp/substr,replacement)
regexp/substr:必需。规定子字符串或要替换的模式的 RegExp 对象。
replacement:必需。一个字符串值。规定了替换文本或生成替换文本的函数。

二、用法

1、用 replace()替换字符串中的字符。

var str="Wo shi Linjianlong!"
console.log(str.replace(/shi/,"jiao"))

2、用 replace()进行全局替换。—-主要加个g开启全局模式

var str="Wo shi Linjianlong! hahaha wo shi linJianlong";
console.log(str.replace(/shi/g,"jiao"))

3、用 replace()确保大写字母的正确性。 —主要用i

text = "javascript Tutorial";
document.write(text.replace(/javascript/i, "JavaScript"));

4、用 replace() 来转换姓名的格式。

name = "Doe, John";
document.write(name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"));

5、用 replace() 来转换引号。

name = '"a", "b"';
document.write(name.replace(/"([^"]*)"/g, "'$1'"));

6、用 replace() 把单词的首字母转换为大写。

name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
    return word.substring(0,1).toUpperCase()+word.substring(1);}
    );
document.write (uw);

猜你喜欢

转载自blog.csdn.net/longgeaisisi/article/details/82694699