chris
chris

Reputation: 36937

Javascript search string for numbers regex maybe?

I have a string like

:21::22::24::99:

And I want to find say if :22: is in said string. But is there a means of searching a string like above for one like I want to match it to with javascript, and if there is, does it involve regex magic or is there something else? Either way not sure how to do it, more so if regex is involved.

Upvotes: 0

Views: 161

Answers (2)

RobG
RobG

Reputation: 147363

You can build the regular expression you need:

function findNumberInString(num, s) {
    var re = new RegExp(':' + num + ':');
    return re.test(s);
}

var s = ':21::22::24::99';
var n = '22';

findNumberInString(n, s);  // true

or just use match (though test is cleaner to me)

!!s.match(':' + n + ':');  // true

Edit

Both the above use regular expressions, so a decimal ponit (.) will come to represent any character, so "4.1" will match "461" or even "4z1", so better to use a method based on String.prototype.indexOf just in case (unless you want "." to represent any character), so per Blender's comment:

function findNumberInString(num, s) {
    return s.indexOf(':' + num + ':') != -1;
}

Upvotes: 2

vdbuilder
vdbuilder

Reputation: 12964

like this:

aStr = ':21::22::24::99:';
if(aStr.indexOf(':22:') != -1){
    //':22:' exists in aStr
}
else{
    //it doesn't
}

Upvotes: 2

Related Questions