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.
The preg_match() function returns whether a match was found in a string.
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 .
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.
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
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).
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With