I am trying to remove the text from the last parentheses within a string using jQuery. I am able to remove the parentheses from the string but the code removes every parentheses and I need the last one to be removed only. For example, I have the following string "This is a (test) string (where) last parentheses (needs) to be (removed) "
I wrote the code below to remove the parentheses and text within the parentheses.
$('p').text(function(_, text) {
return text.replace(/(.*?)/g, '');
});
The code I tried removed all the parentheses from within the string, I need to remove the last parentheses from within the string.
3
Answers
To remove only the last parenthesis and its contents from a string, you can use one of these approaches:
Using regex with a negative lookahead:
lastindexOf
You need to update your regular expression a bit.
(([^()]*))
: This part matches any content within a pair of parentheses.(?=[^()]*$)
: This lookahead asserts that this pair of parentheses is the last one in the string. It checks that there are no more parentheses after the current match.Your regexp:
/(([^()]*))(?=[^()]*$)/
Can you try this;