【问题标题】:Replacing a specific spaces with dashes用破折号替换特定空格
【发布时间】:2022-01-02 10:46:11
【问题描述】:

尝试用破折号替换特定空格并将字符串小写

例如

"1.0 Domain - sub & domain"

"1.0-Domain-sub&domain"

试过

str.replace(/\s+/g, '-').toLowerCase();
-> 1.0-domain---sub-&-domain

【问题讨论】:

    标签: javascript node.js regex


    【解决方案1】:

    您可以在可选的空白字符之间捕获-&,并仅将其替换为捕获的字符,或者使用replacer function 匹配要替换为空字符串的1 个或多个空白字符。

    let str = "1.0 Domain - sub & domain";
    
    str = str.replace(/\s*([&-])\s*|\s+/g, (m, g1) => g1 ? g1 : '-').toLowerCase();
    
    console.log(str)

    【讨论】:

    • 就像一个魅力!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2013-12-11
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多