是否有可能在JavaScript
中執行類似preg_match
的操作PHP
?preg_match在JavaScript中?
我希望能夠從字符串得到兩個數字:
var text = 'price[5][68]';
成兩個分離變量:
var productId = 5;
var shopId = 68;
編輯: 我也用MooTools
如果這將有助於。
是否有可能在JavaScript
中執行類似preg_match
的操作PHP
?preg_match在JavaScript中?
我希望能夠從字符串得到兩個數字:
var text = 'price[5][68]';
成兩個分離變量:
var productId = 5;
var shopId = 68;
編輯: 我也用MooTools
如果這將有助於。
var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);
match [1] match [2]將包含您正在查找的數字。
這應該工作:
var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
var productId = match[1];
var shopId = match[2];
} else {
// no match
}
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
if(!thisRegex.test(text)){
alert('fail');
}
我發現測試表現得更爲的preg_match它提供了一個布爾返回。但是你必須聲明一個RegExp變種。
提示:RegExp在開始和結束時添加它自己的/所以不要傳遞它們。
你也可以用'/\ [(\ d +)\] \ [(\ d +)\] /。test(text)' – FlabbyRabbit 2013-05-07 15:35:19
我同意,當我看到如何重現preg_match的正則表達式測試功能時, ;) – flu 2013-10-15 17:10:23
使用RegExp類構造函數的好處是,如果需要在模式中插入一個變量,它需要一個字符串! – 2017-07-26 04:34:47
對於其他googlers; 'text.match'將返回匹配的結果。所以'var match = text.match(/ price \ [(\ d +)\] \ [(\ d +)\] /)'然後'alert(match [1]);' – Maurice 2012-09-27 14:45:28