[英]How to replace underscores with spaces using a regex in Javascript
How can I replace underscores with spaces using a regex in Javascript?如何在 Javascript 中使用正则表达式将下划线替换为空格?
var ZZZ = "This_is_my_name";
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(" ");
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
方法)..
var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');
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/_/ /
To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, eg str.replaceAll('_', ' ') .要将下划线替换为字符串中的空格,请调用replaceAll()方法,将下划线和空格作为参数传递给它,例如str.replaceAll('_', ' ') 。 The replaceAll method will return a new string where each underscore is replaced by a space. replaceAll 方法将返回一个新字符串,其中每个下划线都被一个空格替换。
const str = 'apple_pear_melon';
// ✅ without regular expression
const result1 = str.replaceAll('_', ' ');
console.log(result1); // 👉️ "apple pear melon"
// ✅ with regular expression
const result2 = str.replace(/_+/g, ' ');
console.log(result2); // 👉️ "apple pear melon"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.