developer tip

JavaScript의 preg_match?

optionbox 2020. 11. 7. 09:15
반응형

JavaScript의 preg_match?


그것은에서 가능 JavaScript처럼 뭔가를 preg_match에서와 PHP?

문자열에서 두 개의 숫자를 얻고 싶습니다.

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

두 개의 분리 된 변수로 :

var productId = 5;
var shopId    = 68;

편집 : MooTools도움이 될 경우 에도 사용 합니다.


JavaScript에는 RegExp원하는 것을 수행 하는 객체가 있습니다. String객체는이 match()당신을 도울 것입니다 기능을.

var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);

var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);

match [1] 및 match [2]에는 찾고있는 숫자가 포함됩니다.


var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');

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

부울 반환을 제공하므로 더 많은 preg_match를 수행하는 테스트를 찾았습니다. 그러나 RegExp var를 선언해야합니다.

팁 : RegExp는 시작과 끝 부분에 자체적으로 추가하므로 전달하지 마십시오.


이것은 작동합니다.

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
}

참고 URL : https://stackoverflow.com/questions/3291289/preg-match-in-javascript

반응형