Remove text between square brackets at the end of string

前端 未结 3 1412
傲寒
傲寒 2021-01-24 03:39

I need a regex to remove last expression between brackets (also with brackets)

source: input[something][something2] target: input[something]

I\'ve tried this, bu

相关标签:
3条回答
  • 2021-01-24 04:08

    Note that \[.*?\]$ won't work as it will match the first [ (because a regex engine processes the string from left to right), and then will match all the rest of the string up to the ] at its end. So, it will match [something][something2] in input[something][something2].

    You may specify the end of string anchor and use [^\][]* (matching zero or more chars other than [ and ]) instead of .*?:

    \[[^\][]*]$
    

    See the JS demo:

    console.log(
       "input[something][something2]".replace(/\[[^\][]*]$/, '')
    );

    Details:

    • \[ - a literal [
    • [^\][]* - zero or more chars other than [ and ]
    • ] - a literal ]
    • $ - end of string

    Another way is to use .* at the start of the pattern to grab the whole line, capture it, and the let it backtrack to get the last [...]:

    console.log(
       "input[something][something2]".replace(/^(.*)\[.*]$/, '$1')
    );

    Here, $1 is the backreference to the value captured with (.*) subpattern. However, it will work a bit differently, since it will return all up to the last [ in the string, and then all after that [ including the bracket will get removed.

    0 讨论(0)
  • 2021-01-24 04:11

    Do not use the g modifier, and use the $ anchor:

    "input[something][something2]".replace(/\[[^\]]*\]$/, '');
    
    0 讨论(0)
  • 2021-01-24 04:28

    try this code

    var str = "Hello, this is Mike (example)";
    
    alert(str.replace(/\s*\(.*?\)\s*/g, ''));

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