js中全部替换字符

本文详细介绍了在JavaScript中使用正则表达式进行字符串替换的方法,包括全局替换、特定字符替换以及特殊字符处理技巧。通过实例演示了如何正确地使用正则表达式来替换字符串中的字符,并特别强调了转义字符的重要性。

对字符串中指定字符替换为另一字符,

str=str.replace(str1,str2);将str中的str1替换为str2。

但是这个在js中无法将所有的str1都替换为str2。

 

呵呵,为了实现全部替换查了个正则:

var opList="abcd,efg";

opList=opList.replace(new RegExp('|',"gm"),',')

执行此语句可正常的将opList串中所有的逗号换为竖杠。

但是当交换逗号和竖杠的位置的时候,得到的结果却是带有很多逗号的串。而不是把竖杠换为逗号。

找了很长时间不知道原因,后来发现竖杠是需要转义的。如下能正确的替换:

var str="fda|fd";
 var str2="";
 str2 = str.replace(//|/g,",");

在JavaScript中,主要使用`str.replace()`方法进行字符替换,有以下两种常见方式: - 只替换第一个查找到的字符:使用`str.replace("需要替换字符串", "新字符串")`的形式。例如`"yyyy-MM-dd-hh-mm-ss".replace("-","/")`,结果为`"yyyy/MM-dd-hh-mm-ss"`。通常,JavaScript的`String replace()`函数只会替换它在字符串中找到的第一个匹配的子符,如`const myMessage = 'this is the sentence to end all sentences'; const newMessage = myMessage.replace('sentence', 'message');`,输出为`this is the message to end all sentences` [^2][^3][^4]。 - 全局替换查找到的字符:使用`str.replace(/需要替换字符串/g, "新字符串")`的形式。例如`"yyyy-MM-dd-hh-mm-ss".replace(/-/g,"/")`,结果为`"yyyy/MM/dd/hh/mm/ss"`。也可以通过创建正则`RegExp`对象来实现全局替换,如`var reg = new RegExp("终古", "g"); var stringObj = "终古人民共和国,终古人民"; var newstr = stringObj.replace(reg, "中国");` [^2][^5]。 示例代码如下: ```javascript // 只替换第一个匹配项 let str1 = "hello world, hello js"; let newStr1 = str1.replace("hello", "hi"); console.log(newStr1); // 全局替换 let str2 = "hello world, hello js"; let newStr2 = str2.replace(/hello/g, "hi"); console.log(newStr2); // 使用RegExp对象进行全局替换 let reg = new RegExp("world", "g"); let str3 = "hello world, hello world"; let newStr3 = str3.replace(reg, "universe"); console.log(newStr3); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值