【问题标题】:How can I perform a str_replace in JavaScript, replacing text in JavaScript?如何在 JavaScript 中执行 str_replace,替换 JavaScript 中的文本?
【发布时间】:2011-07-28 00:33:05
【问题描述】:

我想使用 str_replace 或类似的替代方法来替换 JavaScript 中的某些文本。

var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

应该给

this is some sample text that i dont want to replace

如果您要使用正则表达式,那么在性能方面有何影响? 与内置替换方法的比较。

【问题讨论】:

标签: javascript replace str-replace


【解决方案1】:
var new_text = text.replace("want", "dont want");

【讨论】:

    【解决方案2】:

    你应该这样写:

    var text = "this is some sample text that i want to replace";
    var new_text = text.replace("want", "dont want");
    document.write(new_text);
    

    【讨论】:

      【解决方案3】:

      在 JavaScript 中,您可以在 String 对象上调用 replace 方法,例如"this is some sample text that i want to replace".replace("want", "dont want"),将返回替换后的字符串。

      var text = "this is some sample text that i want to replace";
      var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
      

      【讨论】:

        【解决方案4】:

        您将使用replace 方法:

        text = text.replace('old', 'new');
        

        显然,第一个参数就是您要查找的内容。它也可以接受正则表达式。

        请记住,它确实不会更改原始字符串。它只返回新值。

        【讨论】:

        • 非常感谢'它只会返回,不会改变'!这就是我很长一段时间以来一直在扯头发的原因,直到我看到你的评论......
        • string.replace('old','new') 只会替换字符串中的第一个 'old' 实例。在realmag777的答案中使用带有'g'标志的正则表达式将替换字符串的所有实例。 text = text.replace(/old/g, 'new') 将替换 'old' 的所有实例
        • 不区分大小写怎么样?
        • ^ text.replace(/old/gi, 'new') 将替换所有 'old' 实例为 'new' 不区分大小写(例如 'OLD' 和 'oLd' 将被替换以及)
        【解决方案5】:

        hm.. 你检查了 replace() 吗?

        您的代码将如下所示

        var text = "this is some sample text that i want to replace";
        var new_text = text.replace("want", "dont want");
        document.write(new_text);
        

        【讨论】:

          【解决方案6】:

          更简单:

          city_name=city_name.replace(/ /gi,'_');
          

          用'_'替换所有空格!

          【讨论】:

          • 这是对“str_replace”所做的更准确的翻译(全局)。选择的答案只会替换第一个实例。
          • 不要忘记转义字符,特别是如果您要替换十六进制转义符:例如 \x27 将是 .replace(/\\x3B/g,';')
          【解决方案7】:

          该函数替换只有一次出现..如果您需要替换 多次出现您应该尝试此功能: http://phpjs.org/functions/str_replace:527

          不一定。 查看 Hans Kesting 的答案:

          city_name = city_name.replace(/ /gi,'_');
          

          【讨论】:

            【解决方案8】:

            其他人给你的代码只替换一次,而使用正则表达式会替换它们(就像@sorgit 说的那样)。要将所有“想要”替换为“不想要”,我们使用以下代码:

            var text = "this is some sample text that i want to replace";
            var new_text = text.replace(/want/g, "dont want");
            document.write(new_text);
            

            变量“new_text”将导致“这是一些我不想替换的示例文本”。

            要获得正则表达式的快速指南,请访问:
            http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
            要了解有关str.replace() 的更多信息,请访问:
            https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
            祝你好运!

            【讨论】:

              【解决方案9】:

              所有这些方法都不修改原始值,返回新字符串。

              var city_name = 'Some text with spaces';
              

              第一个空格替换为_

              city_name.replace(' ', '_'); // Returns: "Some_text with spaces" (replaced only 1st match)
              

              使用正则表达式将 所有空格 替换为 _。如果您需要使用正则表达式,那么我建议您使用https://regex101.com/ 进行测试

              city_name.replace(/ /gi,'_');  // Returns: Some_text_with_spaces 
              

              所有空格替换为_不带正则表达式。功能方式。

              city_name.split(' ').join('_');  // Returns: Some_text_with_spaces
              

              【讨论】:

                【解决方案10】:

                已经有多个答案使用str.replace()(对于这个问题来说足够公平)和regex,但你可以使用str.split()join()的组合,这比str.replace()regex更快.

                以下是工作示例:

                var text = "this is some sample text that i want to replace";
                
                console.log(text.split("want").join("dont want"));

                【讨论】:

                  【解决方案11】:

                  您有以下选择:

                  1. 替换第一个匹配项

                  var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
                  var new_text = text.replace('want', 'dont want');
                  // new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
                  console.log(new_text)
                  1. 替换所有匹配项 - 区分大小写

                  var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
                  var new_text = text.replace(/want/g, 'dont want');
                  // new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
                  console.log(new_text)
                  1. 替换所有匹配项 - 不区分大小写

                  var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
                  var new_text = text.replace(/want/gi, 'dont want');
                  // new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
                  console.log(new_text)

                  更多信息 -> here

                  【讨论】:

                    【解决方案12】:

                    添加了满足您要求的方法replace_in_javascript。还发现您在document.write() 中写入了一个字符串"new_text",它应该引用一个变量new_text

                    let replace_in_javascript= (replaceble, replaceTo, text) => {
                      return text.replace(replaceble, replaceTo)
                    }
                    
                    var text = "this is some sample text that i want to replace";
                    var new_text = replace_in_javascript("want", "dont want", text);
                    document.write(new_text);

                    【讨论】:

                      【解决方案13】:

                      如果你真的想要一个等效于 PHP 的 str_replace,你可以使用 Locutus。 PHP 版本的str_replace 支持比JavaScript String.prototype.replace 支持的选项更多。 例如标签:

                      //PHP
                      $bodytag = str_replace("%body%", "black", "<body text='%body%'>");
                      
                      //JS with Locutus
                      var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')  
                      

                      或数组的

                      //PHP
                      $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
                      $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
                      
                      //JS with Locutus
                      var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
                      var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
                      

                      此外,这不使用正则表达式,而是使用 for 循环。如果您不想使用正则表达式但想要简单的字符串替换,您可以使用这样的东西(基于 Locutus)

                      function str_replace (search, replace, subject) {
                      
                        var i = 0
                        var j = 0
                        var temp = ''
                        var repl = ''
                        var sl = 0
                        var fl = 0
                        var f = [].concat(search)
                        var r = [].concat(replace)
                        var s = subject
                        s = [].concat(s)
                      
                        for (i = 0, sl = s.length; i < sl; i++) {
                          if (s[i] === '') {
                            continue
                          }
                          for (j = 0, fl = f.length; j < fl; j++) {
                            temp = s[i] + ''
                            repl = r[0]
                            s[i] = (temp).split(f[j]).join(repl)
                            if (typeof countObj !== 'undefined') {
                              countObj.value += ((temp.split(f[j])).length - 1)
                            }
                          }
                        }
                        return s[0]
                      }
                      var text = "this is some sample text that i want to replace";
                      
                      var new_text = str_replace ("want", "dont want", text)
                      document.write(new_text)

                      更多信息见源代码https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js

                      【讨论】:

                        【解决方案14】:

                        在 Javascript 中,replace 函数可用于将给定字符串中的子字符串替换为新字符串。 用途:

                        var text = "this is some sample text that i want to replace";
                        var new_text = text.replace("want", "dont want");
                        console.log(new_text);
                        

                        你甚至可以在这个函数中使用正则表达式。例如,如果要将所有出现的, 替换为.

                        var text = "123,123,123";
                        var new_text = text.replace(/,/g, ".");
                        console.log(new_text);
                        

                        这里g修饰符用于全局匹配所有可用的匹配项。

                        【讨论】:

                          【解决方案15】:

                          JavaScript 有 replace() String 对象的方法来替换子字符串。此方法可以有两个参数。第一个参数可以是字符串或正则表达式模式(regExp 对象),第二个参数可以是字符串或函数。下面显示了具有两个字符串参数的replace() 方法示例。

                          var text = 'one, two, three, one, five, one';
                          var new_text = text.replace('one', 'ten');
                          console.log(new_text)  //ten, two, three, one, five, one
                          

                          请注意,如果第一个参数是字符串,则仅替换第一次出现的子字符串,如上例所示。要替换所有出现的子字符串,您需要提供带有g(全局)标志的正则表达式。如果您不提供全局标志,即使您提供正则表达式作为第一个参数,也只会替换第一次出现的子字符串。因此,让我们替换上面示例中所有出现的one

                          var text = 'one, two, three, one, five, one';
                          var new_text = text.replace(/one/g, 'ten');
                          console.log(new_text)  //ten, two, three, ten, five, ten
                          

                          请注意,您不要将正则表达式模式用引号括起来,这将使其成为字符串而不是 regExp 对象。要进行不区分大小写的替换,您需要提供额外的标志i,这使得模式不区分大小写。在这种情况下,上述正则表达式将为/one/gi。请注意此处添加的 i 标志。

                          如果第二个参数有一个函数,并且如果有一个匹配的函数,则传递三个参数。函数获取的参数是匹配项、匹配项的位置和原始文本。您需要返回应该替换的匹配项。例如,

                          var text = 'one, two, three, one, five, one';
                          var new_text = text.replace(/one/g, function(match, pos, text){
                          return 'ten';
                          });
                          console.log(new_text) //ten, two, three, ten, five, ten
                          

                          您可以使用函数作为第二个参数来更好地控制替换文本。

                          【讨论】:

                          • 你是唯一一个提到替换能力里面的功能
                          【解决方案16】:

                          使用 React 的 replace substring in a sentence 方法:

                           const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
                              let newStr = "";
                              let i = 0;
                              sentence.split(" ").forEach(obj => {
                                if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
                                  newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
                                  i = i + 1;
                                } else {
                                  newStr = i === 0 ? obj : newStr + " " + obj;
                                  i = i + 1;
                                }
                              });
                              return newStr;
                            };
                          

                          RunMethodHere

                          【讨论】:

                            【解决方案17】:

                            如果你不想使用正则表达式,那么你可以使用这个函数来替换字符串中的所有内容

                            源代码:

                            function ReplaceAll(mystring, search_word, replace_with) 
                            {
                                while (mystring.includes(search_word))
                                {
                                    mystring = mystring.replace(search_word, replace_with);
                                }
                            
                                return mystring;  
                            }
                            

                            使用方法:

                            var mystring = ReplaceAll("Test Test", "Test", "Hello"); 
                            

                            【讨论】:

                              【解决方案18】:

                              你可以使用

                              text.replace('old', 'new')
                              

                              并且一次更改一个字符串中的多个值,例如将#更改为字符串v,将_更改为字符串w:

                              text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
                              

                              【讨论】:

                                【解决方案19】:

                                使用 JS String.prototype.replace 第一个参数应该是正则表达式模式或字符串,第二个参数应该是一个字符串或函数。

                                str.replace(regexp|substr, newSubStr|function);

                                例如:

                                var str = 'this is some sample text that i want to replace'; var newstr = str.replace(/want/i, "dont't want"); document.write(newstr); // this is some sample text that i don't want to replace

                                【讨论】:

                                  【解决方案20】:

                                  使用正则表达式进行字符串替换比使用字符串替换要慢得多。
                                  正如on JSPerf 演示的那样,您可以在创建正则表达式时获得不同级别的效率,但所有这些都比简单的字符串替换要慢得多。 The regex is slower because:

                                  固定字符串匹配没有回溯、编译步骤、范围、字符类或许多其他会减慢正则表达式引擎的功能。当然有优化正则表达式匹配的方法,但我认为在常见情况下它不太可能击败对字符串的索引。

                                  对于在 JS perf 页面上运行的简单测试,我记录了一些结果:

                                  <script>
                                  // Setup
                                    var startString = "xxxxxxxxxabcxxxxxxabcxx";
                                    var endStringRegEx = undefined;
                                    var endStringString = undefined;
                                    var endStringRegExNewStr = undefined;
                                    var endStringRegExNew = undefined;
                                    var endStringStoredRegEx = undefined;      
                                    var re = new RegExp("abc", "g");
                                  </script>
                                  
                                  <script>
                                  // Tests
                                    endStringRegEx = startString.replace(/abc/g, "def") // Regex
                                    endStringString = startString.replace("abc", "def", "g") // String
                                    endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
                                    endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
                                    endStringStoredRegEx = startString.replace(re, "def") // saved regex
                                  </script>

                                  Chrome 68 的结果如下:

                                  String replace:    9,936,093 operations/sec
                                  Saved regex:       5,725,506 operations/sec
                                  Regex:             5,529,504 operations/sec
                                  New Regex String:  3,571,180 operations/sec
                                  New Regex:         3,224,919 operations/sec
                                  

                                  为了这个答案的完整性(借用 cmets),值得一提的是 .replace 仅替换匹配字符的第一个实例。只能用//g 替换所有实例。如果替换多个实例name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); 或更糟while (name.includes(' ')) { name = name.replace(' ', '_') }

                                  ,性能权衡和代码优雅可能会更糟

                                  【讨论】:

                                  • 这很有趣,而且纯字符串替换比正则表达式更快是有道理的。可能值得一提(就像在某些答案中一样).replace 仅替换匹配字符的第一个实例。只能用//g 替换所有实例。如果替换多个实例name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); 或更糟while (name.includes(' ')) { name = name.replace(' ', '_') },性能折衷可能会更糟
                                  【解决方案21】:
                                  function str_replace($old, $new, $text)
                                  {
                                     return ($text+"").split($old).join($new); 
                                  }
                                  

                                  您不需要额外的库。

                                  【讨论】:

                                    【解决方案22】:

                                    在ECMAScript 2021中,可以使用replaceAll可以使用。

                                    const str = "string1 string1 string1"
                                    const newStr = str.replaceAll("string1", "string2");
                                    
                                    console.log(newStr)
                                    //  "string2 string2 string2"
                                    

                                    【讨论】:

                                      【解决方案23】:

                                      最简单的形式如下

                                      如果你只需要替换第一次出现

                                      var newString = oldStr.replace('want', 'dont want');
                                      

                                      如果你想改变所有发生的事情

                                      var newString = oldStr.replace(want/g, 'dont want');
                                      

                                      【讨论】:

                                        【解决方案24】:

                                        ES2021 / ES12

                                        String.prototype.replaceAll()

                                        即使输入模式是字符串,也会尝试提供完全替换选项。

                                        const str = "Backbencher sits at the Back";
                                        const newStr = str.replaceAll("Back", "Front");
                                        console.log(newStr); // "Frontbencher sits at the Front"
                                        

                                        1- String.prototype.replace()

                                        只有当我们将模式作为正则表达式提供时,我们才能进行完整的**替换**。
                                        const str = "Backbencher sits at the Back";
                                        const newStr = str.replace(/Back/g, "Front");
                                        console.log(newStr); // "Frontbencher sits at the Front"
                                        

                                        如果输入模式是字符串,replace() 方法只替换第一次出现。

                                        const str = "Backbencher sits at the Back";
                                        const newStr = str.replace("Back", "Front");
                                        console.log(newStr); // "Frontbencher sits at the Back"
                                        

                                        2-可以使用split和join

                                        const str = "Backbencher sits at the Back";
                                        const newStr = str.split("Back").join("Front");
                                        console.log(newStr); // "Frontbencher sits at the Front"
                                        

                                        【讨论】:

                                          猜你喜欢
                                          • 1970-01-01
                                          • 2013-01-07
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 2013-05-18
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 2012-11-12
                                          相关资源
                                          最近更新 更多