0

how can i find '('+any number+')' in a string to split the string into array like i have this text

"(1)some words (2)other words (3)other words (4)other words ...."and so on

here is what i have tried someString.split(/[0-9]/)

result:"(" ")some words (" ")other words (" ")other words (" ")other words"

this seems to find only numbers from 0 to 9

i need something like ('('+/[0-9]/+')')

R3ter
  • 57
  • 7
  • I think what you'd need most would be to follow a quick regex tutorial before you try to use them. In the meantime, `/\(\d+\)/` might suit your needs – Aaron Feb 27 '19 at 13:16
  • Have you seen https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript – GabrieleMartini Feb 27 '19 at 13:17
  • Possible duplicate of [Regular Expression to get a string between parentheses in Javascript](https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript) – GabrieleMartini Feb 27 '19 at 13:17

2 Answers2

0

Use a regex on \d+ or \(\d+\)

console.log( 
  "(1)some words  (2)other words (3)other words (4)other words .... (10)end"
  .match(/\d+/g) // or \d{1,}
)

Only in brackets using a capturing group:

const re = /\((\d+)\)/g;
while (match = re.exec("(1)some words  (2)other words (3)other number 3 words (4)other words .... (10)end")) {
  console.log(match[1])
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Assuming you want to actually end up with an array of terms, not numbers, we can try doing a regex split on the pattern \(\d+\):

input = "(1)some words  (2)other words (3)other words (4)other words ....";
terms = input.split(/\(\d+\)/);
terms.shift();
console.log(terms);

You have a few problems going on, but as to why your current split is only targeting 0-9, this is because the regex pattern [0-9] just means 0 to 9. Use [0-9]+ or \d+ to target any number of digits.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360