Separate string in jQuery

6

If I have a text string such that:

var cadena1 = "cadena_1";

And I just need to get 1 from the previous string to put it in a variable, how can I do it?

Doing this:

var res = cadena1.split("_");

the result is cadena,1

    
asked by Pavlo B. 23.01.2017 в 12:47
source

3 answers

7

it would be enough to do:

var res = cadena1.split('_')[1]; // segundo elemento del array que se obtiene al hacer split

greetings

    
answered by 23.01.2017 / 12:53
source
8

You can use split() by taking the second element:

var cadena1 = "cadena_1";
var res = cadena1.split("_")[1];
console.log(res);

Or use substring() if you know that there will only be 1 number. With the possibility of values > 9 would use the option of split()

var cadena1 = "cadena_1";
var res = cadena1.substring(cadena1.length-1);
console.log(res);
    
answered by 23.01.2017 в 12:54
4

Just use split ()

var tmp = cadena1.split("_"); //retorna un array
//console.log(tmp);
var num = tmp[1];
console.log(num);
    
answered by 23.01.2017 в 13:54