如何在 JavaScript 中执行 str_replace,替换 JavaScript 中的文本?
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(25)
您将使用
replace
方法:显然,第一个参数就是您要查找的内容。它还可以接受正则表达式。
请记住,它不会更改原始字符串。它仅返回新值。
You would use the
replace
method: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.
更简单:
用“_”替换所有空格!
More simply:
Replaces all spaces with '_'!
所有这些方法都不修改原始值,返回新字符串。
将第一个空格替换为 _
使用正则表达式将所有空格替换为 _。如果您需要使用正则表达式,那么我建议使用 https://regex101.com/ 进行测试
替换 所有空格都带有 _ 不带正则表达式。功能性方式。
All these methods don't modify original value, returns new strings.
Replaces 1st space with _
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
Replaces all spaces with _ without regex. Functional way.
你应该写这样的东西:
You should write something like that :
其他人给你的代码只替换一次出现的情况,而使用正则表达式则替换所有出现的情况(就像 @sorgit 所说)。要将所有“想要”替换为“不想要”,请使用以下代码:
变量“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:
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!
不一定。
请参阅汉斯·凯斯廷的回答:
Not necessarily.
see the Hans Kesting answer:
使用正则表达式进行字符串替换比使用字符串替换要慢得多。
正如 JSPerf 所示,您可以在创建正则表达式时获得不同级别的效率,但所有这些都比简单的字符串替换慢得多。 正则表达式速度较慢,因为:
对于 JS perf 页面上的简单测试运行,我记录了一些结果:
Chrome 68 的结果如下:
为了回答的完整性(借用评论),值得一提的是
.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:
For a simple test run on the JS perf page, I've documented some of the results:
The results for Chrome 68 are as follows:
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 instancesname.replace(' ', '_').replace(' ', '_').replace(' ', '_');
or worsewhile (name.includes(' ')) { name = name.replace(' ', '_') }
嗯..你检查过replace()吗?
你的代码看起来像这样
hm.. Did you check replace() ?
Your code will look like this
JavaScript 有 String 对象的
replace()
方法来替换子字符串。该方法可以有两个参数。第一个参数可以是字符串或正则表达式模式(regExp 对象),第二个参数可以是字符串或函数。下面显示了具有两个字符串参数的replace()
方法的示例。请注意,如果第一个参数是字符串,则仅替换第一次出现的子字符串,如上例所示。要替换所有出现的子字符串,您需要提供带有
g
(全局)标志的正则表达式。如果不提供全局标志,即使您提供正则表达式作为第一个参数,也只会替换第一次出现的子字符串。因此,让我们替换上面示例中所有出现的one
。请注意,不要将正则表达式模式括在引号中,这将使其成为字符串而不是 regExp 对象。要进行不区分大小写的替换,您需要提供额外的标志
i
,这使得模式不区分大小写。在这种情况下,上述正则表达式将是/one/gi
。请注意此处添加的i
标志。如果第二个参数有一个函数并且存在匹配,则该函数将与三个参数一起传递。该函数获取的参数是匹配项、匹配项的位置和原始文本。您需要返回该匹配项应替换为的内容。例如,
您可以使用函数作为第二个参数来更好地控制替换文本。
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 ofreplace()
method having both string arguments is shown below.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 ofone
in the above example.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 thei
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,
You can have more control over the replacement text using a function as the second argument.
在 JavaScript 中,您可以在 String 对象上调用
replace
方法,例如"这是我想要替换的一些示例文本".replace("want", "dont Want"),这将返回替换的字符串。
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.您可以使用
And 一次更改一个字符串中的多个值,例如将 # 更改为字符串 v,将 _ 更改为字符串 w:
You can use
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
使用 str.replace( 已经有多个答案) (这对于这个问题来说足够公平)和
regex
但您可以使用 str.split() 和 join() 在一起,比str.replace()
和regex.
下面是工作示例:
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 thanstr.replace()
andregex
.Below is working example:
如果你真的想要一个与 PHP 的
str_replace
相当的东西,你可以使用 Locutus。 PHP 版本的str_replace
支持的选项比 JavaScriptString.prototype.replace
支持的选项更多。例如 tag:
或 array's
另外,这不使用正则表达式,而是使用 for 循环。如果您不想使用正则表达式但想要简单的字符串替换,您可以使用类似的东西(基于 Locutus )
有关更多信息,请参阅源代码 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 ofstr_replace
support more option then what the JavaScriptString.prototype.replace
supports.For example tags:
or array's
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 )
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js
您有以下选择:
更多信息-> 此处
You have the following options:
More info -> here
在 Javascript 中,replace 函数可用于将给定字符串中的子字符串替换为新字符串。
使用:
您甚至可以在此函数中使用正则表达式。例如,如果想要将所有出现的
,
替换为.
。这里的
g
修饰符用于匹配全局所有可用的匹配项。In Javascript, replace function available to replace sub-string from given string with new one.
Use:
You can even use regular expression with this function. For example, if want to replace all occurrences of
,
with.
.Here
g
modifier used to match globally all available matches.使用React
替换句子中的子字符串
的方法:RunMethodHere
Method to
replace substring in a sentence
using React:RunMethodHere
如果您不想使用正则表达式,那么您可以使用此函数,它将替换字符串中的所有
内容源代码:
如何使用:
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
How to use:
使用 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
ES2021 / ES12
String.prototype.replaceAll()
试图提供完整的替换选项,即使输入模式是字符串也是如此。
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
如果输入模式是字符串,则
replace()
方法仅替换第一个匹配项。2-您可以使用拆分和连接
ES2021 / ES12
String.prototype.replaceAll()
is trying to bring the full replacement option even when the input pattern is a string.
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
If the input pattern is a string,
replace()
method only replaces the first occurrence.2- You can use split and join
您不需要额外的库。
You do not need additional libraries.
在 ECMAScript 2021 中,可以使用
replaceAll
来使用。In ECMAScript 2021, you can use
replaceAll
can be used.最简单的形式如下
只需替换第一个出现的情况,则
如果您不想替换所有出现的情况,则
simplest form as below
if you need to replace only first occurrence
if you want ot repalce all occurenace
JavaScript 中的内置函数是“.replace()”函数。
.replace() 函数的语法如下:
因此,在字符串中,可以使用此内置函数将整个或部分字符串替换为其他值。
例如,让字符串 s 为:“我在 Coding Ninjas 网站的帮助下练习开发。”代码如下:
那么,如果我们打印字符串news,则如下:
“我在 Coding Ninjas 网站的帮助下练习开发。”
此外,您可以多次使用它来替换位于不同位置的字符串的各种文本。
例如,
这些语句将导致以下输出:
“我在编码忍者网站的帮助下练习开发。”
此外,如果您希望用其他文本替换您所编写的多个文本实例,则只会替换该文本的第一个实例。
例如,
它将仅替换第一个“ 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:
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:
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,
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,
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.
添加了一个方法
replace_in_javascript
,它将满足您的要求。还发现您正在document.write()
中写入字符串"new_text"
,该字符串应该引用变量new_text
。Added a method
replace_in_javascript
which will satisfy your requirement. Also found that you are writing a string"new_text"
indocument.write()
which is supposed to refer to a variablenew_text
.