Home > Software engineering >  How to remove part of string that is in parentheses?
How to remove part of string that is in parentheses?

Time:06-16

I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:

const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);

How would I be able to return the string without these last parentheses?

CodePudding user response:

Source: How to remove the last word in a string using JavaScript

Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.

   var str = "Hello my name is (john) (doe) (bob)";
   var lastIndex = str.lastIndexOf("(");

   str = str.substring(0, lastIndex);
   console.log(str);

CodePudding user response:

You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:

^(.*)\([^()]*\)

Regex demo

CodePudding user response:

const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');

console.log(str.slice(0, lastIdxS).trim());

  • Related