【问题标题】:Javascript RegExp Allow Spaces Inside PatternJavascript RegExp 允许模式内的空格
【发布时间】:2022-06-10 19:48:08
【问题描述】:

我需要将所有"*text*" 替换为"<strong>text</strong>"

当传递 text = "normal text *words to be bolded* continue normal text" 时,由于空格,它不起作用,它仅适用于单字文本。

想要的结果:"normal text <strong>words to be bolded</strong> continue normal text"

结果:"normal text *words to be bolded* continue normal text"

我需要这个函数来处理任何文本:

function bold(text){
    reg = /\*(\w+)\*/g
    return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}

【问题讨论】:

    标签: javascript regexp-replace


    【解决方案1】:

    可以使用数组拆分方式。

    const str = "word1 word2 pla pla";
    const newStr = [];
    str.split(" ").forEach((val) => {
      newStr.push(`<strong>${val}</strong> `);
    });
    console.log(newStr);

    【讨论】:

    • 是的,我同意,恐怕这里不是这种情况,虽然这些词可能包含/嵌入在更宽的字符串中
    【解决方案2】:

    您应该允许一组字符存在。现在,您已经修复了字符序列。

    function bold(text){
        reg = /\*([\w\s]+)\*/g
        return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
    }
    

    【讨论】:

    • 这将阻止像!?这样的字符被包含在内。
    • 是的,没错。我没有回答全部要求。
    【解决方案3】:

    我假设通过“要加粗的单词”,您正在尝试匹配任何不是星号的内容。

    function bold(text){
        let reg = /\*([^\*]*)\*/g;
        return text.replaceAll(reg, "<strong>$1</strong>")
    };
    let result = bold("normal1 *bold1 including space!* normal2 *bold2, including space?* normal3"); 
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 2013-05-15
      相关资源
      最近更新 更多