简体   繁体   English

全局使用javascript替换点_?

[英]replacing dots with _ using javascript globally?

im trying to replace all the dots and spaces in " 我试图替换“中的所有点和空格"

var name = "C. S. Lewis"

and replace them with _ 并用_替换它们

and convert it into "C_S_LEWIS" 并将其转换为"C_S_LEWIS"

this is what i tried but it converts the whole thing into underscores ( _ ) 这是我试过但它将整个事物转换成下划线( _

var mystring = "C. S. Lewis";
var find = ".";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "_"));

That's because dots need to be escaped in regular expressions (unless it's part of a character class). 这是因为点需要在正则表达式中进行转义(除非它是字符类的一部分)。 This expression should work: 这个表达式应该有效:

var regex = /[.\s]+/g;

alert(mystring.replace(regex, '_'))

It matches a sequence of at least one period or space, which is then replaced by a single underscore in the subsequent .replace() call. 它匹配至少一个句点或空格的序列,然后在随后的.replace()调用中由单个下划线替换。

Btw, this won't save the new string back into mystring . 顺便说一句,这不会将新字符串保存回mystring For that you need to assign the results of the replacement operation back into the same variable: 为此,您需要将替换操作的结果分配回同一个变量:

mystring = mystring.replace(regex, '_')

The . . means 'any character'. 意思是'任何角色'。 Use \\. 使用\\. to get a literal dot, which means in your regex string you'd have to put \\\\. 得到一个文字点,这意味着在你的regex字符串中你必须放置\\\\. to get a literal underscore followed by a literal dot. 得到一个文字下划线后跟一个文字点。 But I'm not sure why you're making a string first - you could just do this: 但我不确定你为什么要先制作一个字符串 - 你可以这样做:

var find = /\./g;

Of course, that's not what you're looking for - you want not just any dot, but just the dots followed by spaces. 当然,这不是你想要的 - 你不仅需要任何点,而只需要点后跟空格。 That's different: 那不一样:

var find = /\.\s+/g;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM