如何匹配javascript中的特定号码?

时间:2022-05-03 09:18:03

I have a situation where, in javascript, I need to compare the contents of one string to see if it contains the exact same number in another string that could contain multiple numbers.

我有一种情况,在javascript中,我需要比较一个字符串的内容,看看它是否包含可能包含多个数字的另一个字符串中的完全相同的数字。

For example.

Source: "1234" Comparison: "1000 12345 112345 1234 2000"

资料来源:“1234”比较:“1000 12345 112345 1234 2000”

It should only match on the 1234 and not on the 12345 or 112345, etc.

它应仅匹配1234而不是12345或112345等。

It also needs to match if the source occurs at the beginning or end of the line.

如果源出现在行的开头或结尾,它也需要匹配。

How would I go about doing that?

我该怎么做呢?

3 个解决方案

#1


Use regex:

"1000 12345 112345 1234 2000".match("\\b1234\\b")

#2


What about using the word boundary to match the number:

如何使用单词边界来匹配数字:

var p = /\b1234\b/;
var match = p.exec("1000 12345 112345 1234 2000")

#3


This is probably one of the less efficient ways of doing it. Do a javascript string split() on the space character then do a search on the array of strings you get back.

这可能是效率较低的方法之一。在空格字符上执行javascript字符串split(),然后搜索您返回的字符串数组。

#1


Use regex:

"1000 12345 112345 1234 2000".match("\\b1234\\b")

#2


What about using the word boundary to match the number:

如何使用单词边界来匹配数字:

var p = /\b1234\b/;
var match = p.exec("1000 12345 112345 1234 2000")

#3


This is probably one of the less efficient ways of doing it. Do a javascript string split() on the space character then do a search on the array of strings you get back.

这可能是效率较低的方法之一。在空格字符上执行javascript字符串split(),然后搜索您返回的字符串数组。