Javascript 如何在Javascript中使用正则表达式用空格替换下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5356133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace underscores with spaces using a regex in Javascript
提问by Karim Ali
How can I replace underscores with spaces using a regex in Javascript?
如何在Javascript中使用正则表达式用空格替换下划线?
var ZZZ = "This_is_my_name";
回答by pepkin88
If it is a JavaScript code, write this, to have transformed string in ZZZ2
:
如果它是 JavaScript 代码,请编写此代码以将字符串转换为ZZZ2
:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.replace(/_/g, " ");
also, you can do it in less efficient, but more funky, way, without using regex:
此外,您可以在不使用正则表达式的情况下以较低效率但更时髦的方式完成此操作:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.split("_").join(" ");
回答by Hyman
Regular expressions are not a tool to replace texts inside strings but just something that can search for patterns inside strings. You need to provide a context of a programming language to have your solution.
正则表达式不是替换字符串中文本的工具,而是可以搜索字符串中模式的工具。您需要提供编程语言的上下文才能获得解决方案。
I can tell you that the regex _
will match the underscore but nothing more.
我可以告诉你,正则表达式_
将匹配下划线,但仅此而已。
For example in Groovy you would do something like:
例如,在 Groovy 中,您可以执行以下操作:
"This_is_my_name".replaceAll(/_/," ")
===> This is my name
but this is just language specific (replaceAll
method)..
但这只是特定于语言的(replaceAll
方法)。
回答by Adam Batkin
Replace "_" with " "
用。。。来代替 ” ”
The actual implementation depends on your language.
实际实现取决于您的语言。
In Perl it would be:
在 Perl 中,它将是:
s/_/ /g
But the truth is, if you are replacing a fixed string with something else, you don't need a regular expression, you can use your language/library's basic string replacement algorithms.
但事实是,如果您用其他东西替换固定字符串,则不需要正则表达式,您可以使用您的语言/库的基本字符串替换算法。
Another possible Perl solution would be:
另一种可能的 Perl 解决方案是:
tr/_/ /
回答by Aamir Afridi
var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');