简体   繁体   中英

how to replace or remove all text strings outside of parenthesis in javascript

I am very new to Regex and I am trying to remove all text outside the parenthesis and only keep everything inside the parenthesis.

For example 1,

Hello,this_isLuxy.(example)

to this:

(example)

Example 2:remove everything after the period

luxySO_i.example

to this:

luxySO_i

Using JS + Regex? Thanks so much!

For this simple string, you can use indexOf and substring functions:

var openParenthesisIndex = str.indexOf('(');
var closedParenthesisIndex = str.indexOf(')', openParenthesisIndex);
var result = str.substring(openParenthesisIndex, closedParenthesisIndex + 1);

Ok, if you want to use regex, then it's going to be a bit complicated. Anyways, here you go:

var str = "Hello,this_(isL)uxy.(example) asd (todo)";
var result = str.replace(/[^()](?=([^()]*\([^()]*\))*[^()]*$)/g, '');
console.log(result); // "(isL)(example)(todo)"

In short, this replaces any non () character, which is followed by zero or more balanced parenthesis. It will fail for nested or non-balanced parenthesis though.

To keep only things inside parenthesis you can use

s.replace(/.*?(\([^)]*\)).*?/g, "$1")

meaning is:

  • .*? any sequence of any char (but the shortest possible sequence)
  • \\( an open parenthesis
  • [^)]* zero or more chars that are NOT a closed parenthesis
  • \\) a close parenthesis
  • .*? any sequence of any char (but the shortest possible)

the three middle elements are what is kept using grouping (...) and $1 .

To remove everything after the first period the expression is simply:

s.replace(/\..*/, "")

meaning:

  • \\. the dot character ( . is special and would otherwise mean "any char")
  • .* any sequence of any characters (ie everything until the end of the string)

replacing it with the empty string

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