Sooraj
Sooraj

Reputation: 10567

Javascript best way to extract particular text from a string

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

Answers (2)

Pranav C Balan
Pranav C Balan

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

user4095822
user4095822

Reputation:

You can simple use the split function.

like this 'xyz-12-1'.split('-')[1] and 'xyz-12-1'.split('-')[2]

Upvotes: 1

Related Questions