Reputation: 10567
I have a string like xyz-12-1
. Numbers can be anything , or even the text can be anything. I'm trying to extract the numbers 12
and 1
in the string.
I tried and succeeded with the following code.
var test = "node-23-1";
test = test.replace(test.substring(0, test.indexOf("-") + 1), ""); //remove the string part
var node1 = test.substring(0, test.indexOf("-")); //get first number
var node2 = test.substring(test.indexOf("-") + 1, test.length); //get second number
alert(node1);
alert(node2);
I feel this is too much code. It is working fine. But is there a more readable , more efficient way to do the same ?
Upvotes: 0
Views: 156
Reputation: 115222
You can use match()
or split()
var res = 'xyz-12-1'.split('-'); // get values by index 1 and 2
var res1 = 'xyz-12-1'.match(/(\d+)-(\d+)/); // get values by index 1 and 2
document.write('<pre>' + JSON.stringify(res) +'\n'+ JSON.stringify(res1) + '</pre>');
Upvotes: 3
Reputation:
You can simple use the split function.
like this 'xyz-12-1'.split('-')[1]
and 'xyz-12-1'.split('-')[2]
Upvotes: 1