tags:

views:

46

answers:

3

With Javascript how would I search the first three letters in a string and see if they match "ABC"? Thanks

+4  A: 

Using a regular expression:

str.match(/^ABC/);

or using the substring method:

str.substring(0, 3) == 'ABC';
Sinan Ünür
Hi Sinan, it is saffer to use first method?
SourceRebels
'Safer' in what sense? Security-wise, I do not see a problem with either. If we are talking about the availability, I believe `substring` has been available since JS 1.0 and `match` was added later in JS 1.2.
Sinan Ünür
The first method is slower. I don’t know what you mean by “safer” though.
Nate
For such a simple need, its actually better to use the substring method, as it is significantly faster.
seanmonstar
@seanmonstar and @Nate agreed.
Sinan Ünür
+2  A: 
if (/^ABC/.test(aString)) {

}
dfa
A: 
"ABCDEF".match(/^ABC/)
Chetan Sastry