skip to Main Content

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


  1. To remove only the last parenthesis and its contents from a string, you can use one of these approaches:

    1. Using regex with a negative lookahead:

       $('p').text(function(_, text) {
       return text.replace(/([^()]*)(?!.*([^()]*))/g, '');
       });
      
    2. lastindexOf

       $('p').text(function(_, text) {
       const start = text.lastIndexOf('(');
       const end = text.lastIndexOf(')');
       if (start !== -1 && end !== -1) {
           return text.slice(0, start) + text.slice(end + 1);
       }
       return text;
       });
      
    Login or Signup to reply.
  2. 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: /(([^()]*))(?=[^()]*$)/

    Login or Signup to reply.
  3. Can you try this;

    var message = 'This is a (test) string (where) last parentheses (needs) to be (removed)';
    
    message= message.replace(/(([^()]*))$/,"$1");
    
    console.log(message);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search