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

发布于 2024-10-29 10:58:43 字数 402 浏览 9 评论 0原文

我想使用 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

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

I want to use str_replace or its similar alternative to replace some text in 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);

should give

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

一袭水袖舞倾城 2024-11-05 10:58:43

您将使用 replace 方法:

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

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

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

You would use the replace method:

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

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.

好倦 2024-11-05 10:58:43

更简单:

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

用“_”替换所有空格!

More simply:

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

Replaces all spaces with '_'!

猛虎独行 2024-11-05 10:58:43

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

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

All these methods don't modify original value, returns new strings.

var city_name = 'Some text with spaces';

Replaces 1st space with _

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

Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/

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

Replaces all spaces with _ without regex. Functional way.

city_name.split(' ').join('_');  // Returns: Some_text_with_spaces
做个少女永远怀春 2024-11-05 10:58:43

你应该写这样的东西:

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

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
不气馁 2024-11-05 10:58:43

其他人给你的代码只替换一次出现的情况,而使用正则表达式则替换所有出现的情况(就像 @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-表达式/
要了解有关 str.replace() 的更多信息,请访问此处:
https://developer.mozilla.org/en-US /docs/JavaScript/Reference/Global_Objects/String/replace
祝你好运!

The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like @sorgit said). To replace all the "want" with "not want", us this code:

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);

The variable "new_text" will result in being "this is some sample text that i dont want to replace".

To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!

等风来 2024-11-05 10:58:43

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

不一定。
请参阅汉斯·凯斯廷的回答:

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

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

Not necessarily.
see the Hans Kesting answer:

city_name = city_name.replace(/ /gi,'_');
巴黎夜雨 2024-11-05 10:58:43

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

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

对于 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

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

Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:

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.

For a simple test run on the JS perf page, I've documented some of the results:

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

The results for Chrome 68 are as follows:

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

From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }

千紇 2024-11-05 10:58:43
var new_text = text.replace("want", "dont want");
var new_text = text.replace("want", "dont want");
盗心人 2024-11-05 10:58:43

嗯..你检查过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);

hm.. Did you check replace() ?

Your code will look like this

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
蔚蓝源自深海 2024-11-05 10:58:43

JavaScript 有 String 对象的 replace() 方法来替换子字符串。该方法可以有两个参数。第一个参数可以是字符串或正则表达式模式(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

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

JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.

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

Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.

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

Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.

If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,

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

You can have more control over the replacement text using a function as the second argument.

对你再特殊 2024-11-05 10:58:43

在 JavaScript 中,您可以在 String 对象上调用 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

In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.

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
木森分化 2024-11-05 10:58:43

您可以使用

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

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

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

You can use

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

And to change multiple values in one string at once, for example to change # to string v and _ to string w:

text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
Spring初心 2024-11-05 10:58:43

使用 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"));

There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.

Below is working example:

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

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

东北女汉子 2024-11-05 10:58:43

如果你真的想要一个与 PHP 的 str_replace 相当的东西,你可以使用 Locutus。 PHP 版本的 str_replace 支持的选项比 JavaScript String.prototype.replace 支持的选项更多。
例如 tag:

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

或 array's

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

If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports.
For example tags:

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

or array's

//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");

Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on 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)

for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js

妄想挽回 2024-11-05 10:58:43

您有以下选择:

  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)

更多信息-> 此处

You have the following options:

  1. Replace the first occurrence

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. Replace all occurrences - case sensitive

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. Replace all occurrences - case insensitive

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)

More info -> here

人间☆小暴躁 2024-11-05 10:58:43

在 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 修饰符用于匹配全局所有可用的匹配项。

In Javascript, replace function available to replace sub-string from given string with new one.
Use:

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

You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..

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

Here g modifier used to match globally all available matches.

同尘 2024-11-05 10:58:43

使用React替换句子中的子字符串的方法:

 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

Method to replace substring in a sentence using React:

 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

↘人皮目录ツ 2024-11-05 10:58:43

如果您不想使用正则表达式,那么您可以使用此函数,它将替换字符串中的所有

内容源代码:

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"); 

If you don't want to use regex then you can use this function which will replace all in a string

Source Code:

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

    return mystring;  
}

How to use:

var mystring = ReplaceAll("Test Test", "Test", "Hello"); 
动听の歌 2024-11-05 10:58:43

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

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

例如:

var str = '这是我要替换的一些示例文本';
var newstr = str.replace(/想要/i, "不想要");
文档.write(newstr); // 这是一些我不想替换的示例文本

Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.

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

Ex:

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

芸娘子的小脾气 2024-11-05 10:58:43

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()

We can do a full **replacement** only if we supply the pattern as a regular expression.

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-您可以使用拆分和连接

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

ES2021 / ES12

String.prototype.replaceAll()

is trying to bring the full replacement option even when the input pattern is a string.

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()

We can do a full **replacement** only if we supply the pattern as a regular expression.

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

If the input pattern is a string, replace() method only replaces the first occurrence.

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

2- You can use split and join

const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
雨的味道风的声音 2024-11-05 10:58:43
function str_replace($old, $new, $text)
{
   return ($text+"").split($old).join($new); 
}

您不需要额外的库。

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

You do not need additional libraries.

樱花细雨 2024-11-05 10:58:43

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

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

console.log(newStr)
//  "string2 string2 string2"

In ECMAScript 2021, you can use replaceAll can be used.

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

console.log(newStr)
//  "string2 string2 string2"
柏拉图鍀咏恒 2024-11-05 10:58:43

最简单的形式如下

只需替换第一个出现的情况,则

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

如果您不想替换所有出现的情况,则

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

simplest form as below

if you need to replace only first occurrence

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

if you want ot repalce all occurenace

var newString = oldStr.replace(want/g, 'dont want');
只为一人 2024-11-05 10:58:43

JavaScript 中的内置函数是“.replace()”函数。
.replace() 函数的语法如下:

" <string_name>.replace('text to edit', 'text to replace it with' ); "

因此,在字符串中,可以使用此内置函数将整个或部分字符串替换为其他值。

例如,让字符串 s 为:“我在 Coding Ninjas 网站的帮助下练习开发。”代码如下:

let news=s.replace("website", "Website");

那么,如果我们打印字符串news,则如下:
“我在 Coding Ninjas 网站的帮助下练习开发。”

此外,您可以多次使用它来替换位于不同位置的字符串的各种文本。
例如,

let news=s
.replace("development", "Development")
.replace("with", "With");
console.log(news);

这些语句将导致以下输出:
“我在编码忍者网站的帮助下练习开发。”

此外,如果您希望用其他文本替换您所编写的多个文本实例,则只会替换该文本的第一个实例。
例如,

let news = s.replace("the", "The");
console.log(news);

它将仅替换第一个“ the”,结果如下:
“我在编码忍者网站的帮助下练习开发。”
因此,如果要替换字符串子字符串的所有实例,则必须使用“ .replaceall()”方法。

现在,如果要用一个文本替换多个子字符串,则可以使用以下命令语法:
让News = S.Replace(/实践|开发/G,“研究”);
控制台.log(新闻);
输出将是:
“我在 Coding Ninjas 网站的帮助下学习。”

另外,您可以尝试使用以下命令语法来将“.replace()”函数与正则表达式一起使用。
让新闻= s.replace(/the/g,“ the”);
控制台.log(新闻);

这些命令的输出如下:
“我在 The Coding Ninjas 网站的帮助下练习开发。”
这里,“/g”指定所有出现的子字符串“the”都应该替换为“The”子字符串。

The in-built function in JavaScript is the ".replace()" function.
The syntax of the .replace() function is as follows:

" <string_name>.replace('text to edit', 'text to replace it with' ); "

Hence, in a string, the whole or part of the string can be replaced with some other value using this in-built function.

For example, let the string s be: "I practice development with the help of the Coding Ninjas website." And the code is as follows:

let news=s.replace("website", "Website");

Then, if we print the string news, it will be as follows:
"I practice development with the help of the Coding Ninjas Website."

Also, you can use it multiple times to replace various texts of the string located in different positions.
Like,

let news=s
.replace("development", "Development")
.replace("with", "With");
console.log(news);

These statements will result in the following output:
"I practice Development With the help of the Coding Ninjas website."

Also, if there is more than one instance of the text you have written that you want to replace with some other text, only the first instance of the text will be replaced.
For example,

let news = s.replace("the", "The");
console.log(news);

It will only replace the first 'the', resulting as follows:
"I practice development with The help of the Coding Ninjas website."
Hence, if you want to replace all the instances of a substring of the string, you would have to use the ".replaceAll()" method.

Now, if you want to replace multiple substrings with one text, you can use the following syntax of the commands:
let news = s.replace(/practice|development/g, "study");
console.log(news);
The output will be:
"I study study with the help of the Coding Ninjas website."

Also, you can try the following syntax of the command to use the ".replace()" function with regular expressions.
let news=s.replace(/the/g, "The");
console.log(news);

The output of these commands will be as the following:
"I practice development with The help of The Coding Ninjas website."
Here, the "/g" specifies that all the occurrences of the substring "the" should be replaced with "The" substring.

执笏见 2024-11-05 10:58:43

添加了一个方法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);

Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable 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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文