Javascript regex returns null trying to get text between parentheses

Trying to get "Table 2" or any other table number that may be (sometimes 2 digits) in a variable. Any idea why this returns null ?

  var productText = '25-08-12 Boat Cruise (Table 2)'; var rgx = /^\(\)$/; var newText = productText.match(rgx); alert(newText); 
+4
source share
3 answers

Use the following instead:

 var rgx = /\(([^)]+)\)/; var match = productText.match(rgx); var newText = match && match[1]; // newText value will be "Table 2" if there is match; null otherwise 

When you have /^\(\)$/ , you are actually trying to match the string "()" , no more, no less. Instead, you should match anywhere in the text, ( , store everything between it and the next ) in the capture group ([^)]+) so that you can subsequently refer to the captured group using match[1] .

If you want only a number, use /\(Table (\d+)\)/ .

+7
source
 var rgx = /\((.*)\)/ 

Captures the table number in the group.

Your regex currently says

'give me () at the beginning (^) and end of line ($)'.

0
source

The value ^ means the beginning of the line and

$ means end of line.

In addition, you need something to match the text inside () , for example:. .*

Given that /^\(\)$/ will only match () .

Then a working example could be:

 var productText = '25-08-12 Boat Cruise (Table 2)'; var rgx = /\(.*\)/; var newText = productText.match(rgx)[0]; newText = newText.replace('(',''); newText = newText.replace(')',''); alert(newText); 

After seeing what you need , I would recommend using jQuery data .

0
source

Source: https://habr.com/ru/post/1435702/


All Articles