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
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 stringAnother 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.
Do not use the g
modifier, and use the $
anchor:
"input[something][something2]".replace(/\[[^\]]*\]$/, '');
try this code
var str = "Hello, this is Mike (example)";
alert(str.replace(/\s*\(.*?\)\s*/g, ''));