2016-02-18 33 views
0

我有一個字符串,如xyz-12-1。數字可以是任何東西,甚至文字可以是任何東西。我試圖提取字符串中的數字121。 我試過併成功使用下面的代碼。JavaScript從字符串中提取特定文本的最佳方法

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);

我覺得這是太多的代碼。 它工作正常。但是,還有更可讀,更有效的方法來做同樣的事嗎?

+1

' 'XYZ-12-1'.split(' - ')[1]'或'' XYZ-12-1'.match(/(\ d +) - ( \ d +)/)[1]' –

+0

完美。請把它寫成答案,以便我可以接受它。 –

回答

3

您可以使用match()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>');

1

你可以簡單的使用分割功能。

這樣'xyz-12-1'.split('-')[1]'xyz-12-1'.split('-')[2]

相關問題