Skip to content Skip to sidebar Skip to footer

How To Extract Text Which Are Outside And Inside A Bracket From A Sentence Through Javascript Or Jquery

I have a sentence stored in a variable.That sentence I need to extract into 3 parts which I have mentioned in other 3 variable in my code,for now I have hard coded in the variabl

Solution 1:

The best option in this case is to create a regular expression.

In your case (if I got it right) you have a sentence consisting of:

  1. Some text
  2. Open parenthesis '('
  3. More text
  4. The word 'or'
  5. More text
  6. Close parenthesis ')'

So you want a regex to match the format above and you want to capture the items 1, 3 and 5.

Here, I made the regex for you: /^(.*) ?\((.*) or (.*)\)$/

Now, using the function exec(string) you can match the desired string and capture the desired sections from it.

regex = /^(.*) ?\((.*) or (.*)\)$/;maintext = "Welcome to project,are you (1. Existing user or 2. new user)";matches = regex.exec(maintext);text_split1 = matches[1];text_split2 = matches[2];text_split3 = matches[3];

Notice that I didn't use matches[0]. That's because this is the full match from the regex, which, in this case, would be the full string you had at first.

Also, notice that the regex may fail with any of the texts inside the parenthesis contain the full word 'or', which is being used to separate the two portions of the string. You must secure this won't happen, or maybe use some special character to separate the two texts instead of the word.

Solution 2:

I suggest you take a look at the Split, Substring and IndexOf methods.

For example if you wanted to grab what's inside the parenthesis you could do

var inside_split = maintext.substring(maintext.indexOf( "(" ) + 1, maintext.indexOf( ")" ) )

and then whats outside of it

var outside_split = maintext.substring(0, maintext.indexOf("(") - 1)

or with Split

var split_Text = maintext.split("(") 

Careful with Split here because it'll result in the last parenthesis being included in.

Array [ "Welcome to project,are you ", "1. Existing user or 2. new user)" ]

and from that you can Split the two options with

split_Text[1].split("or")

which results in

Array [ "1. Existing user ", " 2. new user)" ]

and then manipulate the remaining closing parenthesis

Post a Comment for "How To Extract Text Which Are Outside And Inside A Bracket From A Sentence Through Javascript Or Jquery"