
正文
jquery replace用法汇总
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
//只替换匹配到的第一个目标
var str="Visit Microsoft! Microsoft"
document.write(str.replace(/Microsoft/,"W3School"))
结果:Visit W3School! Microsoft
//全局搜索(替换所有匹配到的目标)
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"));
//对大小写不敏感的搜索()
text = "JAVAScript Tutorial";
document.write(text.replace(/javascript/i, "JavaScript"));
//全局匹配并且忽略大小写
text.replace(/javascript/ig,"JavaScript");
结果:JavaScript Tutorial
//replace() 来转换姓名的格式
name = "Doe, John";
document.write(name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"));
结果:John Doe
// replace() 来转换引号
name = '"a", "b"';
document.write(name.replace(/"([^"]*)"/g, "'$1'"));
结果:'a', 'b'
// replace() 把单词的首字母转换为大写
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);
结果:Aaa Bbb Ccc






