Javascript 用破折号替换空格并使所有字母小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1983648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:14:10  来源:igfitidea点击:

Replace spaces with dashes and make all letters lower-case

javascriptstringreplace

提问by M.E

I need to reformat a string using jQuery or vanilla JavaScript

我需要使用 jQuery 或 vanilla JavaScript 重新格式化字符串

Let's say we have "Sonic Free Games".

假设我们有"Sonic Free Games".

I want to convert it to "sonic-free-games".

我想将其转换为"sonic-free-games".

So whitespaces should be replaced by dashes and all letters converted to small letters.

因此,空格应替换为破折号,并将所有字母转换为小写字母。

Any help on this please?

请对此有任何帮助吗?

回答by CMS

Just use the String replaceand toLowerCasemethods, for example:

只需使用 StringreplacetoLowerCase方法,例如:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the gflag on the RegExp, it will make the replacement globallywithin the string, if it's not used, only the first occurrence will be replaced, and also, that RegExpwill match one or more white-space characters.

注意 上的g标志RegExp,它将在字符串中全局替换,如果不使用它,则只替换第一次出现,并且RegExp匹配一个或多个空白字符。

回答by yurin

Above answer can be considered to be confusing a little. String methods are not modifyingoriginal object. They returnnew object. It must be:

上面的回答可以认为有点混乱。字符串方法不会修改原始对象。他们返回新对象。肯定是:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

回答by Eesa

You can also use splitand join:

您还可以使用splitjoin

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

回答by Matias

@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).

@CMS 的回答很好,但我想指出您可以使用这个包:https: //github.com/sindresorhus/slugify,它为您完成并涵盖了许多边缘情况(即德语变音、越南语、阿拉伯语) 、俄语、罗马尼亚语、土耳其语等)。

回答by Abdo-Host

var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
console.log(str);
console.log(str.toLowerCase())