我想做的是: 拿一个字符串
这样做的原因是从用户输入
生成友好的URL这就是我到目前为止所有这些
var str = "This is a really bad Url _, *7% !";
result1 = str.replace(/\s+/g, '-').toLowerCase();
alert(result1);
答案 0 :(得分:3)
这可以解决问题
var str = "This is a really bad Url _, *7% !";
result1 = str.replace(/[^a-zA-Z0-9\s]/g, '') // Remove non alphanum except whitespace
.replace(/^\s+|\s+$/, '') // Remove leading and trailing whitespace
.replace(/\s+/g, '-') // Replace (multiple) whitespaces with a dash
.toLowerCase();
alert(result1);
结果:
this-is-a-really-bad-url-7
答案 1 :(得分:0)
你可以这样做
var output=input.replace(/[^A-Za-z\d\s]+/g,"").replace(/\s+/g," ").toLowerCase();
答案 2 :(得分:0)
我只是扩展你已经得到的东西:首先将空格转换为连字符,然后用空字符串替换除字母,数字和连字符之外的所有内容 - 最后转换为小写:
var str = "This is a really bad Url _, *7% !";
result1 = str.replace(/\s+/g, '-').replace(/[^a-zA-Z\d-]/g, '').toLowerCase();
alert(result1);
你还需要考虑你想对字符串中的初始连字符(' - ')做什么。我上面的代码将保留它们。如果您也想删除它们,请将第二行更改为
result1 = str.replace(/[^A-Za-z\d\s]/g, '').replace(/\s+/g, '-').toLowerCase();
答案 3 :(得分:0)
var str = "This is a really bad Url _, *7% !";
result1 = str
.replace(/[^A-Za-z\d\s]+/g, "") //delete all non alphanumeric characters, don't touch the spaces
.replace(/\s+/g, '-') //change the spaces for -
.toLowerCase(); //lowercase
alert(result1);
答案 4 :(得分:0)
我看了所有这些,有些人错过了一些东西。
var stripped = string.toLowerCase() // first lowercase for it to be easier
.replace(/^\s+|\s+$/, '') // THEN leading and trailing whitespace. We do not want "hello-world-"
.replace(/\s+/g, '-') // THEN replace spaces with -
.replace(/[^a-z0-9-\s]/g, '');// Lastly