Pawan
Pawan

Reputation: 32321

How to Extract the number after a certain word

I have got names in the array as

868_KK_0_KK_0tab1_checkbox
868_KK_1_KK_0tab2_checkbox
868_ZZ_0_ZZ_0tab3_checkbox
868_ZZ_0_ZZ_0tab5_checkbox

Exactly after word 'tab' there is a number .

Is it possible to extract these numbers and push them to a array

This is my code

Its just a sample code with no logic

http://jsfiddle.net/nx33jez6/5/

var temp_arry = [];

var jsonarray = [
{
    "name": "868_KK_0_KK_0tab1_checkbox"
}
,
 {
    "name": "868_KK_1_KK_0tab1_checkbox"
}
,
 {
    "name": "868_ZZ_0_ZZ_0tab3_checkbox"
}
,
 {
"name": "868_ZZ_1_ZZ_0tab2_checkbox"
}
];


for (var i = 0; i < jsonarray.length; i++) {
    var name = jsonarray[i].name;
}

Could you please let me know how to do this .

Upvotes: 0

Views: 51

Answers (4)

Arne
Arne

Reputation: 6240

Or without regexp:

arr.forEach(function(v){
  nr = v.split('_checkbox')[0].split('b')[1]; 
});

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could use regular expression, as:

var pattern = /tab(\d+)/,
    arr = [];
for (var i = 0; i < jsonarray.length; i++) {
    var name = jsonarray[i].name;
    arr.push(name.match(pattern)[1]);
}
console.log(arr);

where \d+ matches one or more digit and parenthesis () around it is used to remember the matched number

Demo

Upvotes: 3

Amit Joki
Amit Joki

Reputation: 59232

You could use Array.map and then use Array.split on "tab" and take second element and split on _ and then return the first element

var arr = inputArr.map(function(str){
   return str.split("tab")[1].split("_")[0];
});

Upvotes: 0

atmd
atmd

Reputation: 7490

You can use a regex match, then remove the 'tab' word from the matches, like this:

var temp_arry = [];

for (var i = 0; i < jsonarray.length; i++) {
    var name = jsonarray[i].name;
    var tab = name.match(/tab[0-9]/)[0].replace('tab', '');
    temp_arry.push(tab);
}

console.log(temp_arry);

This shows you all the steps to get to what you want, although like @DemoUser answer it can be done more concisely

Upvotes: 0

Related Questions