Grab snippet of a string between () in Javascript

Asked

Viewed 236 times

-1

I have a text string in the following format:

Size 35 (5 units)

How can I get only the numbers inside the parentheses, ignoring everything else?

2 answers

1

Assuming there are no nested parentheses, for example "(5 abc (7 xyz))", and that within parentheses there is only one occurrence of the number (no cases like "(123 abc 456 xyz 789)"), a way of doing:

let s = 'Tamanho 35 (5 Unidades), abc 123 (456 xyz) etc 999';
for (const match of s.matchAll(/\([^)\d]*(\d+)[^)\d]*\)/g))
    console.log (match[1]);

The idea of regex is to take something in parentheses, indicated by \( and \) - parentheses have special significance in regex and I need to escape them with \ to be interpreted as the characters themselves ( and ).

Next we have [^)\d]*: zero or more characters that are not ) and neither \d (a digit from 0 to 9).

Then we have \d+, indicating one or more digits, then zero or more characters other than the right-digit parentheses.

The chunk corresponding to the digits I put in parentheses to form a capture group, so I can pick up its contents later with match[1] (since it’s the first pair of parentheses, then it’s group 1).


If you have cases like "(123 abc 456 xyz 789)" (more than one number between parentheses), so a solution would first take the content between parentheses and then take the numbers from within it:

let s = 'Tamanho 35 (5 Unidades), abc 123 (123 abc 456 xyz 789) etc 999';
for (const conteudoParenteses of s.matchAll(/\(([^)]+)\)/g)) {
    for (const numero of conteudoParenteses[1].match(/\d+/g))
        console.log(numero);
}

Now I just use [^)]+ (one or more characters other than )) to pick up the contents of the parentheses, and then use \d+ (one or more digits) to get all the numbers inside it.

-3

Save. You can use the Split function as listed here.

So you can use Split to save the text after the ' ( ' and then repeat the process, giving a Split in the Space character.

You can use the concept of structuring to make code cleaner.

Example:

resultado = stringExemplo.split("(");

This will return an Array containing ["Size 35" , "5 Units)"]

As only the second part interests you, you can do so:

[,resultado] = stringExemplo.split("(");

With this you would have only the second part ["5 Units)"]

I think I can understand it. There’s another interesting link here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.