我有这个字符串 "Gem.Buitentemperatuur (etmaal)"
我想替换所有空格、大写字母和特殊字符,这样我就可以结束
"gem_buitentemperatuur_etmaal"
最佳答案
试试这个
var yourStr = "Gem. Buitentemperatuur (etmaal)";
var newStr = yourStr.replace(/\s+/g, "_").replace(/\W+/g, "").toLowerCase();
//gem_buitentemperatuur_etmaal
.replace()用于操作你的字符串,一个简单的正则表达式被传递给这个和你想要用
替换它的值首先我们替换空格。
/ <- start the regex
\s <- match whitespace character
+ <- matches one or more times
/ <- end the regex.
我们将其替换为您的下划线 .replace(/\s+/g, "_")
然后查找并匹配所有非单词字符。
/ <- start the regex
\W <- match all non word characters (everything but a-z, A-Z, 0-9 and _)
+ <- matches one or more times
/ <- end the regex
这部分看起来像这样 .replace(/\W+/g, "")
结束 /
之后的 g
代表全局查找整个字符串,而不仅仅是第一个匹配项。
这是一个 fiddle
关于Javascript 使用正则表达式替换空格和其他字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21190742/