简体   繁体   中英

How to use Regular Expression in this case?

I have got a variable as 30_KK_1_KK_2

How can i get the value after first KK_ and second KK_ ?

so that the output for First KK_ is 1 and

for the second KK_ it is 2

I have tried it this way

var str =  "30_KK_1_KK_2";
var n[] = str.split('_KK_');
alert(n[0]);
alert(n[1]);

You have several typos.

1) No string quotes around the string constant

2) var n[] is not valid... simply var n

3) You need to get elements 1 and 2 as element 0 is "30"

var str =  "30_KK_1_KK_2";
var n = str.split('_KK_');
alert(n[1]);
alert(n[2]);

JSFiddle: http://jsfiddle.net/TrueBlueAussie/w3mLgowc/1/

A regular expression is probably overkill for such a simple problem (and the delimiter is fixed).

If you want to really use Regex you can try this code :

var str =  "30_KK_1_KK_2";
regex = /.*KK_(\d*)_KK_(\d*)/g;
value_1 = str.replace(regex,"$1");
value_2 = str.replace(regex,"$2");
alert(value_1);
alert(value_2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM