How can I perform a str_replace in JavaScript, replacing text in 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.
号
您将使用
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/要了解更多有关
使用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()?
您的代码将如下所示
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中,您在字符串对象上调用
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有字符串对象的
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 |
请注意,如果第一个参数是字符串,则仅替换第一个出现的子字符串,如上面的示例所示。要替换所有出现的子字符串,需要提供一个带有
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对象。要进行不区分大小写的替换,需要提供额外的标志
如果第二个参数有一个函数,并且有一个匹配的,那么函数将通过三个参数传递。函数得到的参数是匹配、匹配位置和原始文本。您需要返回应该替换的匹配项。例如,
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()(这对于这个问题来说是足够公平的)和
下面是工作示例:
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的
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); |
号
这里,
用react法测定
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
埃多克斯1〔9〕
前任:
埃多克斯1〔10〕
1 2 3 4 | function str_replace($old, $new, $text) { return ($text+"").split($old).join($new); } |
。
您不需要其他库。
增加了一个方法
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); |
号