【问题标题】:Keep all alpha and numeric characters and turn white space into -保留所有字母和数字字符并将空白变为 -
【发布时间】:2016-05-14 04:56:11
【问题描述】:

我想做的是: 取一个字符串

  1. 删除任何非字母和数字字符。
  2. 我也在尝试将任何空白变成-,(多个空白将变成一个-)
  3. 全部转换为小写

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

这就是我目前所拥有的一切

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

【问题讨论】:

  • 在这种情况下所需的输出是"this-is-a-really-bad-url-7-" ?
  • 好吧,那么你有很多答案可以选择^^

标签: javascript regex


【解决方案1】:

这可以解决问题

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

【讨论】:

  • 我没有打扰,因为输入可能是一个标题,但你是对的,它更安全。已编辑!
  • str.replace(/[^a-zA-Z0-9\s]/g, '') 将在到达 .replace(/\s+/g, ' 之前替换空格-')
【解决方案2】:

你可以这样做

var output=input.replace(/[^A-Za-z\d\s]+/g,"").replace(/\s+/g," ").toLowerCase();

【讨论】:

    【解决方案3】:
    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); 
    

    【讨论】:

    • 这与我的解决方案完全相似..除了alet...:P
    • 是的,我想我会删除我的,你先回答
    【解决方案4】:

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

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

    【讨论】:

    • 哇,这速度很快,谢谢。我该怎么做才能删除下划线?
    • 这不会取代_
    • @Anirudh 很好,你可以用 A-Za-z 替换 \w - 我更新了答案
    【解决方案5】:

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

    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
    

    【讨论】:

    • 我在项目中使用的内容: var stripped = string.toLowerCase().replace(/^\s+|\s+$/, '').replace(/\s+/g, ' -').replace(/[^a-z0-9-_\s]/g, '');
    猜你喜欢
    • 2023-03-16
    • 2019-05-26
    • 2017-09-03
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多