It depends. You could
string.match(/^abc$/)
But this does not correspond to the following line: 'the first 3 letters of the alphabet are abc. Not abc123'
I think you want to use \ b (word boundaries)
var str = 'the first 3 letters of the alphabet are abc. not abc123'; var pat = /\b(abc)\b/g; console.log(str.match(pat));
Real-time example: http://jsfiddle.net/uu5VJ/
If the first solution works for you, I would advise against using it.
That means you might have something like the following:
var strs = ['abc', 'abc1', 'abc2'] for (var i = 0; i < strs.length; i++) { if (strs[i] == 'abc') { //do something } else { //do something else } }
While you can use
if (str[i].match(/^abc$/g)) { //do something }
This will be significantly more resource intensive. For me, the general rule is that a conditional expression is used for simple string comparisons, since a more dynamic pattern uses a regular expression.
more info about regex's JavaScript: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
matchew Jun 09 '11 at 20:26 2011-06-09 20:26
source share