M.E*_*M.E 222 javascript string replace
我需要使用jQuery或vanilla JavaScript重新格式化字符串
让我们说我们有"Sonic Free Games".
我想把它转换成"sonic-free-games".
所以空格应该用短划线代替,所有字母都换成小写字母.
对此有何帮助?
CMS*_*CMS 492
只需使用String replace和toLowerCase方法,例如:
var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"
Run Code Online (Sandbox Code Playgroud)
注意它上面的g标志RegExp,它将在字符串中全局替换,如果没有使用,只会替换第一个匹配项,并且还会RegExp匹配一个或多个空白字符.
yur*_*rin 30
上面的答案可以被认为是混淆了一点.字符串方法不修改原始对象.他们返回新对象.肯定是:
var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str
Run Code Online (Sandbox Code Playgroud)
Ees*_*esa 28
您还可以使用split和join:
"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
Run Code Online (Sandbox Code Playgroud)
小智 16
一种非常简单的方法是使用 JavaScript String ReplaceAll() 方法。
"Sonic Free Games".replaceAll(' ', '-').toLowerCase(); //sonic-free-games
Run Code Online (Sandbox Code Playgroud)
对于像这样的简单替换,正则表达式通常是多余的。
这更简单且更具可读性。
但是,如果您仍然需要正则表达式,也可以通过此方法使用它们。请参阅moz 文档以获取示例。
如果您需要 IE 支持,则需要一个 polyfill。
小智 7
如果你的项目中有lodash,你可以尝试kebabCase
_.kebabCase('Sonic Free Games')
Run Code Online (Sandbox Code Playgroud)
https://lodash.com/docs/4.17.15#kebabCase
var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
console.log(str);
console.log(str.toLowerCase())Run Code Online (Sandbox Code Playgroud)