views:

206

answers:

3

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.

For example.

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

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

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

How would I go about doing that?

+4  A: 

Use regex:

"1000 12345 112345 1234 2000".match("\\b1234\\b")
altCognito
\b1234\b might be a better choice if you want to test near the start/end of lines.
miccet
Won't match the first or last numbers
Binary Worrier
Whoops, good point!
altCognito
I had tried \b1234\b before without results. I didn't realize that when using via the constructor (new RegExp()) that I need to escape the \ for it to work. "\\b" was what I was missing. Thank you.
tribule
if you only want to check the occurence of the number, I'd suggest using `test()` from RegExp and not `match()`, ie `new RegExp('\\b' + num + '\\b').test('1000 12345 112345 1234 2000')`
Christoph
+1  A: 

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.

sjobe
Oh and if you plan on using the list of numbers for other things in your code, having an array of the numbers in the list might make life a little easier for you.
sjobe
good answer, but you could make it better by replacing "do a search" with "do a lookup: the split will effectively return a hashtable"
annakata
hmmm, what with the key-value pairs in the hashtable be ?
sjobe
+2  A: 

What about using the word boundary to match the number:

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