用破折号替换空格并使所有字母小写 [英] Replace spaces with dashes and make all letters lower-case
本文介绍了用破折号替换空格并使所有字母小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用 jQuery 或 vanilla JavaScript 重新格式化字符串
I need to reformat a string using jQuery or vanilla JavaScript
假设我们有 Sonic 免费游戏"
.
我想把它转换成sonic-free-games"
.
所以空格应该用破折号代替,所有的字母都应该转换成小写字母.
So whitespaces should be replaced by dashes and all letters converted to small letters.
对此有什么帮助吗?
推荐答案
只需使用字符串 replace
和 toLowerCase
方法,例如:
Just use the String replace
and toLowerCase
methods, for example:
var str = "Sonic Free Games";
str = str.replace(/s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"
注意RegExp
上的g
标志,它会在字符串内全局 进行替换,如果不使用,只替换第一个出现将被替换,并且 RegExp
将匹配一个或多个空白字符.
Notice the g
flag on the RegExp
, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp
will match one or more white-space characters.
这篇关于用破折号替换空格并使所有字母小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文