JavaScript/regex: Remove text between parentheses

前端 未结 5 1566
陌清茗
陌清茗 2020-11-29 00:41

Would it be possible to change

Hello, this is Mike (example)

to

Hello, this is Mike

using JavaScript with

相关标签:
5条回答
  • 2020-11-29 01:02

    I found this version most suitable for all cases. It doesn't remove all whitespaces.

    For example "a (test) b" -> "a b"

    "Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

    0 讨论(0)
  • 2020-11-29 01:03

    If you need to remove text inside nested parentheses, too, then:

            var prevStr;
            do {
                prevStr = str;
                str = str.replace(/\([^\)\(]*\)/, "");
            } while (prevStr != str);
    
    0 讨论(0)
  • 2020-11-29 01:06

    Try / \([\s\S]*?\)/g

    Where

    (space) matches the character (space) literally

    \( matches the character ( literally

    [\s\S] matches any character (\s matches any whitespace character and \S matches any non-whitespace character)

    *? matches between zero and unlimited times

    \) matches the character ) literally

    g matches globally

    Code Example:

    var str = "Hello, this is Mike (example)";
    str = str.replace(/ \([\s\S]*?\)/g, '');
    console.log(str);
    .as-console-wrapper {top: 0}

    0 讨论(0)
  • 2020-11-29 01:10
    "Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");
    

    Result:

    "Hello, this is Mike"
    
    0 讨论(0)
  • 2020-11-29 01:14
    var str = "Hello, this is Mike (example)";
    
    alert(str.replace(/\s*\(.*?\)\s*/g, ''));
    

    That'll also replace excess whitespace before and after the parentheses.

    0 讨论(0)
提交回复
热议问题