关于替换:如何在JavaScript中执行str_replace,替换JavaScript中的文本?

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

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

1
2
3
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");

应该给

1
this is some sample text that i dont want to replace

If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.


您将使用replace方法:

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

很明显,第一个论点就是你想要的。它还可以接受正则表达式。

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


更简单地说:

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

将所有空格替换为"u"!


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

1
var city_name = 'Some text with spaces';

将第一个空格替换为_

1
city_name.replace(' ', '_'); // Returns: Some_text with spaces

使用regex替换所有空格。如果您需要使用regex,那么我建议您使用https://regex101.com测试它。/

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

用不带regex的_u替换所有空格。功能性方式。

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


你应该这样写:

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


that function replaces only one occurrence.. if you need to replace
multiple occurrences you should try this function:
http://phpjs.org/functions/str_replace:527

不一定。参见Hans Kesting的答案:

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


其他人给您的代码只替换一次出现,而使用正则表达式则全部替换(如@sorgit所说)。要将所有"想要"替换为"不想要",我们将使用以下代码:

1
2
3
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.craitography.com/davechild/crait-sheets/regular-expressions/要了解更多有关str.replace()的信息,请访问:https://developer.mozilla.org/en-us/docs/javascript/reference/global_objects/string/replace祝你好运!


使用regex替换字符串要比使用字符串替换慢得多。如JSPerf所示,您可以在创建regex时具有不同的效率级别,但所有这些效率都比简单的字符串替换慢得多。regex速度较慢,因为:

Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.

对于JSPerf页面上的简单测试运行,我已经记录了一些结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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");



// 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

铬68的结果如下:

1
2
3
4
5
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

为了这个答案的完整性(借用注释),值得一提的是,.replace只替换匹配字符的第一个实例。它只能用//g替换所有实例。如果替换多个实例name.replace(' ', '_').replace(' ', '_').replace(' ', '_');或更糟的while (name.includes(' ')) { name = name.replace(' ', '_') },性能权衡和代码优雅可能会更糟。


嗯。是否选中replace()?

您的代码将如下所示

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


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

1
2
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


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

1
2
3
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标志(global)的正则表达式。如果不提供全局标志,则即使将正则表达式作为第一个参数提供,也只替换第一次出现的子字符串。因此,让我们替换上面例子中所有出现的one

1
2
3
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标志。

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

1
2
3
4
5
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

您可以使用函数作为第二个参数对替换文本进行更多的控制。


1
var new_text = text.replace("want","dont want");

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

下面是工作示例:

1
2
3
var text ="this is some sample text that i want to replace";

console.log(text.split("want").join("dont want"));


你可以用

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

同时更改一个字符串中的多个值,例如更改为字符串V和字符串W:

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

如果你真的想要一个与PHP的str_replace等价的,你可以使用ochtus。php版本的str_replace支持更多的选项,而不是javascriptString.prototype.replace所支持的选项。例如,标签:

1
2
//PHP
$bodytag = str_replace("%body%","black","<body text='%body%'>");

1
2
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')

或数组的

1
2
3
//PHP
$vowels = array("a","e","i","o","u","A","E","I","O","U");
$onlyconsonants = str_replace($vowels,"","Hello World of PHP");

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

此外,它不使用regex,而是使用for循环。如果您不想使用regex,但想要简单的字符串替换,您可以使用类似的东西(基于ochtus)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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/ochtus/blob/master/src/php/strings/str_replace.js


您有以下选项:

  • 替换第一个匹配项
  • 1
    2
    3
    4
    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
    2
    3
    4
    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
    2
    3
    4
    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)

    更多信息->此处


    在javascript中,用新的函数替换给定字符串中的子字符串。用途:

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

    甚至可以将正则表达式用于此函数。例如,如果想用.替换所有出现的,

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

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


    用react法测定replace substring in a sentence

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     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;
      };

    运行方法此处


    如果不想使用regex,则可以使用此函数替换字符串中的所有内容。

    源代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function ReplaceAll(mystring, search_word, replace_with)
    {
        while (mystring.includes(search_word))
        {
            mystring = mystring.replace(search_word, replace_with);
        }

        return mystring;  
    }

    如何使用:

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


    使用js String.prototype.replace第一个参数应该是regex模式或字符串,第二个参数应该是字符串或函数。

    埃多克斯1〔9〕

    前任:

    埃多克斯1〔10〕


    1
    2
    3
    4
    function str_replace($old, $new, $text)
    {
       return ($text+"").split($old).join($new);
    }

    您不需要其他库。


    增加了一个方法replace_in_javascript,可以满足您的要求。还发现您在document.write()中编写了一个字符串"new_text",它应该是指一个变量new_text

    1
    2
    3
    4
    5
    6
    7
    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);