Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match in JavaScript?

Is it possible in JavaScript to do something like preg_match does in PHP ?

I would like to be able to get two numbers from string:

var text = 'price[5][68]'; 

into two separated variables:

var productId = 5; var shopId    = 68; 

Edit: I also use MooTools if it would help.

like image 915
hsz Avatar asked Jul 20 '10 14:07

hsz


People also ask

What is the use of Preg_match () method?

The preg_match() function returns whether a match was found in a string.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

How to use preg_match() function of PHP in JavaScript?

In JavaScript, we don’t have a built-in function as the preg_match () function of PHP, but we can achieve the same functionality to check the match portion of a string using a regular expression pattern and JavaScript default method match (), which is used on string values.

What is the return value of the preg_match() method?

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

What is match in JavaScript?

The value to search for, as a regular expression. An array containing the matches. null if no match is found. match () is an ES1 feature (JavaScript 1997).

What does the preg_match () function return?

The preg_match () function returns whether a match was found in a string. Required. Contains a regular expression indicating what to search for Required. The string in which the search will be performed


1 Answers

JavaScript has a RegExp object which does what you want. The String object has a match() function that will help you out.

var matches = text.match(/price\[(\d+)\]\[(\d+)\]/); var productId = matches[1]; var shopId    = matches[2]; 
like image 69
godswearhats Avatar answered Sep 24 '22 13:09

godswearhats