简体   繁体   English

替换javascript字符串中的任何字符

[英]Replace any character in a javascript string

I want convert this string: 我要转换此字符串:

string with characters like áéíóú

to

#################################

This "parágrafo".replace(/\\wW*/g, "#") returns "###á#####" "parágrafo".replace(/\\wW*/g, "#")返回"###á#####"

One option is using repeat() 一种选择是使用repeat()

 let str = 'string with caracthers like áéíóú'; let result = "#".repeat(str.length); console.log(result); 

Doc: repeat() Doc: repeat()

The other answers using .repeat() are probably better ways to do this. 使用.repeat()的其他答案可能是执行此操作的更好方法。 This answer mainly serves to explain what's wrong with your code and how it could be done correctly. 该答案主要用于解释您的代码出了什么问题以及如何正确完成。

\\w doesn't match accented letters for some reason, that's why á ends up in the output. \\w由于某些原因与重音字母不匹配,这就是á最终出现在输出中的原因。 But even if this weren't a problem, it wouldn't match the spaces between words. 但是,即使这不是问题,也不会匹配单词之间的空格。

You can use . 您可以使用. , which matches any character except newline. ,它匹配除换行符以外的任何字符。

 console.log("string with caracthers like áéíóú`".replace(/./g, "#")); 

If you also want to replace newlines with # , add the s modifier. 如果您还想用#替换换行符,请添加s修饰符。

 console.log(`string with caracthers like áéíóú and also newlines`.replace(/./gs, "#")); 

Oops, that's a very new feature in ES2018, not available in all browsers yet. 糟糕,这是ES2018中的一项非常新功能,并非在所有浏览器中都可用。 You can use /.|\\ng for better portability. 您可以使用/.|\\ng以获得更好的可移植性。

 console.log(`string with caracthers like áéíóú and also newlines`.replace(/.|\\n/g, "#")); 

"#".repeat("string with characters".length)

无需更换。

repeat() cannot be used in IE so I will suggest looping over to the str length to get string with value # . 不能在IE中使用repeat() ,所以我建议循环到str长度以获取带有值#字符串。

 let str = 'string with caracthers like áéíóú'; let result =''; for(var i=0; i<str.length; i++){ result += '#'; } console.log(result); 

It looks like your regex lost a few characters somewhere (and gained a * ). 看起来您的正则表达式在某处丢失了几个字符(并获得了* )。 It should be /[\\w\\W]/ instead: 应该是/[\\w\\W]/

 var str = "parágrafo".replace(/[\\w\\W]/g, "#"); console.log(str); 

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

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