使用JavaScript从URL中提取数字?

3
var exampleURL = '/example/url/345234/test/';
var numbersOnly = [?]

路径中的/url//test部分始终相同。

请注意,我需要在/url//test之间的数字。在上面的示例URL中,占位符单词“example”有时也可能是数字,但在这种情况下不应匹配。只匹配/url//test之间的数字。

谢谢!

3个回答

10
var exampleURL = '/example/url/345234/test/';

// this will remove all non-numbers
var numbers = exampleURL.replace(/[\D]/g, '');

// or you can split the string and take only that 3rd bit
var numbers = exampleURL.split(/\//)[3];

// or match with a regex
var numbers = exampleURL.match(/\/(\d+)\/test\//)[1];

5

以下是相关内容:

var result;
result = value.match(/\/url\/([0-9]+)\/test/);
// use result[1] to get the numbers (the first capture group)

这取决于 /url//test 部分,因为你说它们是可靠的。更一般地,这将匹配字符串中的 第一个 数字序列:

var result;
result = value.match(/[0-9]+/);
// use result[0] (not result[1]), which is the total match

正则表达式是一个非常有用的工具。

注意:在上面的代码中,可以使用\d代替[0-9],表示数字。但我不这样做,因为我的正则表达式技能很弱,我总是记不住它(而且即使我记住了,我也总是记不清它是所有数字还是所有非数字[这是\D——你看到我的困惑了吧])。当我以后阅读时,我发现[0-9]非常清晰明了。其他人可能会觉得\d更清晰明了,但对我来说,列出范围的明确性更好。


1

适用的正则表达式是

matches = exampleURL.match('/\/.+\/url/([0-9]+)\/test\//');

我认为是正确的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接