preg_match in JavaScript?

2019-01-17 13:49发布

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.

5条回答
虎瘦雄心在
2楼-- · 2019-01-17 14:08
var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
    var productId = match[1];
    var shopId = match[2];
} else {
    // no match
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-17 14:11

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+)\]/);
查看更多
萌系小妹纸
4楼-- · 2019-01-17 14:12

This should work:

var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
查看更多
混吃等死
5楼-- · 2019-01-17 14:23
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');

if(!thisRegex.test(text)){
    alert('fail');
}

I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.

TIP: RegExp adds it's own / at the start and finish, so don't pass them.

查看更多
beautiful°
6楼-- · 2019-01-17 14:24
var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);

match[1] and match[2] will contain the numbers you're looking for.

查看更多
登录 后发表回答