Reputation: 1447
I'm confused why in http://regexr.com/3bcns, my ^#
isn't matching #hello-link
, which is a string that begins with a hashtag.
This is what I want to do:
if ((/^\.\./).test(link)) {
alert('link starts with ..');
} else if (!(/#/).test(link)) {
alert('does not contain #');
} else if ((/^#/).test(link)) {
alert('link begins with a #');
}
Also, I'm curious: is there any reason why people prefer to use .test
instead of .match
when using regexes in javascript?
Upvotes: 0
Views: 161
Reputation: 565
Regex.test(str)
returns a Boolean telling whether or not a match is present. This is the most straightforward check to perform if the only thing you care about is whether or not a match exists.
String.match(regex)
returns the text of the match, or null if there is no match. This is more useful if you need to know what the match actually is. (Edited to reflect Oriol's correction.)
Upvotes: 1
Reputation: 3903
Why not check the first character of the string?
function start_with_hash(str){
return str[0]=='#';
}
Upvotes: 1