Javascript从字符串中提取特定文本的最佳方法

Javascript best way to extract particular text from a string

本文关键字:文本 最佳 方法 字符串 提取 Javascript      更新时间:2023-09-26

我有一个像xyz-12-1这样的字符串。数字可以是任何东西,甚至文本也可以是任何东西。我正在尝试提取字符串中121的数字。我尝试并成功使用以下代码。

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

我觉得这是太多的代码。它工作正常。但是有没有一种更易读、更有效的方法呢?

您可以使用

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

您可以简单地使用拆分功能。

像这样'xyz-12-1'.split('-')[1]'xyz-12-1'.split('-')[2]