简体   繁体   中英

JavaScript Remove the parentheses using loops

I'm trying to achieve this "exampleexample" from this "example(unwanted thing)example", so task is to remove everything inside the parentheses as well as the parentheses. Trying to acheve this using loops, with current code I'm getting "example)example", thanks in advance!

const removeParentheses = function(s){
  let arr = s.split("");
 
  for(let i=0;i<arr.length;i++){
    if(arr[i] === "("){
      while(arr[i] !== ")"){
        arr.splice(i, 1);
      }
    }
  }
  
  return arr.join("");
}

If there's no nesting, I'd use a regular expression instead - match ( , followed by non- ) ,s followed by a ) :

const removeParentheses = s => s.replace(/\([^)]*\)/g, '');
  • \\( - literal (
  • [^)]* - zero or more non- ) s
  • \\) - literal )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM