0

I have:

var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'

and I want to split from (East xr) (301-LT_King_St_PC) only as follow :

var result = text.split('(')
result = (East xr) (301-LT_King_St_PC)
  • So, in words, you want "Everything after (and including) the first open bracket `(`"? – DBS Nov 29 '21 at 15:33
  • 1
    Does this answer your question? [javascript, regex parse string content in curly brackets](https://stackoverflow.com/questions/9792427/javascript-regex-parse-string-content-in-curly-brackets). It's not exactly clear what your end result should be. Could you post more examples of inputs/outputs or explain the logic to translate from `text` to `result`? – WOUNDEDStevenJones Nov 29 '21 at 15:34
  • @DBS yes, Everything between the first '(' and the second ')' – Ahmad Bassam Bkerat Nov 29 '21 at 15:35

4 Answers4

3

You can use a regular expression with the match function to get this done. Depending on how you want the result try one of the following:

var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'
console.log('one string:', text.match(/\(.*\)/)[0])
console.log('array of strings:', text.match(/\([^\)]*\)/g))

The first does what you seem to be asking for - a single output of everything between the first ( and the second ). It does this by searching for /\(.*\)/ which is a regex that says "everything in between the parentheses".

The second match splits it into all parenthesised strings using /\([^\)]*\)/g which is a regex that says "each parenthesised string" but the g at the end says "all of those" so an array of each is given.

Always Learning
  • 5,510
  • 2
  • 17
  • 34
2

You can do it using substring() and indexOf() :

var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)';
var result = text.substring(text.indexOf('('));
console.log(result);
Tom
  • 4,972
  • 3
  • 10
  • 28
0

You're quite close with your current method. One way you could try this is to use multiple characters within your split

var result = text.split(") (") 
# Output -> result = ["(East xr", "301-LT_King_St_PC)"]

From here, some string manipulation could get rid of the brackets.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Alternatively you can also use String.match and join its result:

const text = 'LTE CSSR (East xr) (301-LT_King_St_PC)';
const cleaned = text.match(/\(.+[^\)]\)/).join(` `);
console.log(cleaned);
KooiInc
  • 119,216
  • 31
  • 141
  • 177