保留所有字母和数字字符,并将空白处改为-

Keep all alpha and numeric characters and turn white space into -

本文关键字:空白处 数字字符 保留      更新时间:2023-09-26

我想做的是:取字符串

  1. 删除任何不是字母和数字字符的内容
  2. 我还试图把任何空白变成一个-,(多个空白将变成一个)
  3. 全部转换为小写

这样做的原因是从用户输入的生成一个友好的URL

到目前为止,这就是我的全部

var str = "This is    a really bad Url _, *7% !";
result1 = str.replace(/'s+/g, '-').toLowerCase();
alert(result1); 

这可以实现

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

您可以执行此

var output=input.replace(/[^A-Za-z'd's]+/g,"").replace(/'s+/g," ").toLowerCase();
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); 

我只想扩展一下您已经得到的内容:首先将空格转换为连字符,然后用空字符串替换除字母、数字和连字符之外的所有内容,最后转换为小写:

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();

我看了所有这些,有些遗漏了一些东西。

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