js中replace替换方法


定义:

replace()方法用于在字符串中用一些字符替换另一些字符,或者替换一个与正则表达式匹配的子串。返回替换后的字符串,且原字符串不变

var newStr = str.replace(regexp|substr, newSubStr|function)

regexp/substr: 规定子字符串或者要替换的模式的RegExp对象。如果访值是字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为RegExp对象。

newSubStr/function: 一个字符串值。规定了替换文本或生成替换文本的函数。

1.简单的字符串替换

let str = 'hello world';
let str1 = str.replace('hello', 'new');
console.log(str1) //new world
console.log(str) //hello world

2.正则替换,正则全局匹配需要加上g,否则只会匹配第一个

let str = 'hello world';
let str2 = str.replace(/o/,'zql');
let str3 = str.replace(/o/g,'zql');
console.log(str2) //hellzql world
console.log(str3) //hellzql wzqlrld

3.一些常用的特殊的定义

1)$':表示匹配字符串右边的文本

let str = 'hello world';
let str4 = str.replace(/hello/g, "$'");
let str5 = str.replace(/o/g, "$'");
console.log(str4) // world world
console.log(str5) //hell world wrldrld

2) $`(tab键上方的字符):表示匹配字符串文本左边的文本

let str = 'hello world';
let str6 = str.replace(/world/,"$`");
console.log(str6) //hello hello 

3)$$: 表示插入一个$

let str = '¥2000.00';
let str7 = str.replace(/¥/,"$$");
console.log(str7) //$2000.00

4. 当第二个参数是函数时

将所有单词首字母改为大写

let str = 'please make heath your first proprity';
str1 = str.replace(/\b\w+\b/g, function (word) {
    console.log('匹配正则的参数',word);
    return word[0].toUpperCase() + word.slice(1);
});
console.log(str1); //Please Make Heath Your First Proprity

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM