Home >Web Front-end >JS Tutorial >How to replace all strings in javascript

How to replace all strings in javascript

藏色散人
藏色散人Original
2021-05-10 14:37:463842browse

javascript替换所有字符串的方法:1、通过“function(FindText, RepText){...}”方法替换所有字符串;2、通过“function(reallyDo, replaceWith){...}”替换所有字符串。

How to replace all strings in javascript

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

js中替换所有字符串的2种解决办法

js本身不提供replaceAll()方法的,所以要替换所有字符串需要自己写一个这样的方法,总结了网上几种写法如下:
方法一:

<script type="text/javascript">
//创建replaceAll()函数
 String.prototype.replaceAll = function (FindText, RepText) {
          return this.replace(new RegExp(FindText, "g"), RepText);
        }
        var str = "shingfkhshsnf";
        //用法,把所有n替换成w
        str= str.replaceAll("n","w")
         document.write(str)
  </script>

replaceAll的另一种写法,其实都差不多

//replaceAll的另一种写法,其实都差不多
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);  
    } else {  
        return this.replace(reallyDo, replaceWith);  
    }  
} 

//补充,另一种简化的写法
var str = "dddd-dsss"
//替换中间的“-”,写法如下:
var newStr = str.replace(new RegExp(&#39;-&#39;, &#39;gm&#39;), &#39;&#39;);

结果:

How to replace all strings in javascript
方法二:

<script type="text/javascript">
//替换格式如下
//str.replace(/需要替换的字符串/g,"新字符串");

var str = "shingfkhshsnf";
 //用法,把所有n替换成w
 str= str.replace(/n/g,"w");
 document.write(str)
   </script>

结果:

How to replace all strings in javascript
场景:
有一个很重要的场景会用到这个替换功能,那就是在实际开发中,后台返回的json字符串需要转化成json,但是直接转化会有失败的情况,原因是有些中文的字符串里有换行符,必须把换行符替换了才能格式化成功,格式化之前可以复制代码去网上在线json格式化工具校验试试就知道了
如下:

//替换json换行符操作
JSON.parse(myJson.replace(/\n/g, ""))

推荐学习:《javascript高级教程

The above is the detailed content of How to replace all strings in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn