js字符串替换的方法(replace替换多个字符用法详解)

 分类:js知识时间:2023-03-15 07:30:01点击:

php中有对一个字符串中的指定字符进行替换的方法,在web前端 javascript 脚本中也有字符串替换的方法,而且还非常的简单。接下来我们就说一说,javascrpt 中对字符串进行替换的方法。

一、JavaScript replace() 方法

replace():方法用于在指定的字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

1、语法:

obj.replace(regexp/substr,replacement)

2、参数:

obj:要操作的字符串
regexp/substr:必需。要查找的字符串或一个正规表达式
replacement:必需。要替换的字符或字符串,也可以是生成它们的函数。

3、返回值:

返回被替换以后的字符串

二、js 替换字符串

1、js代码

<script>
 var str = 'hello hello world';
 // /hello/ 与 "hello" 作用是一样的,只是写法不同
 // str2 = str.replace(/hello/,'hi');
 str2 = str.replace("hello", 'hi');
 console.log(str2);
</script>

2、运行结果:

hi hello world

3、注意:

上面的示例中,只能替换第一个要查找匹配的字符串。

三、js 替换所有查找到的字符串

1、js代码

<script>
 var str = 'hi hi world';
 str2 = str.replace(/hi/g, 'hello');
 console.log(str2);
</script>

2、输出结果:

hello hello world

四、js 不区分大小写进行查找和替换的字符串

1、js代码:

<script>
 var str = 'hi Hi world';
 str2 = str.replace(/hi/gi, 'hello');
 console.log(str2);
</script>

2、输出结果:

hello hello world
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址: