How To Check If A String Is An Anchor Tag?
Whats the best way to check if a string is an anchor tag in JS? Some examples: Link //returns true //returns false Is the
Solution 1:
You can use Regex for this:
functionisAnchor(str){
return/^\<a.*\>.*\<\/a\>/i.test(str);
}
Demo
var testStrings = [
'<a href="./page">Hello</a>', // true'<a>Hi</a>', // true'<a href=\'test.php\'>Yo</a>', // true'<A HREF=\'test.php\'>UPPERCASE</A>', // true - not case-sensitive'test', // false'<a href="./page">Hello', // false - tag not closed'<span>Hi again</span>'// false
];
for(var i=0; i<testStrings.length; i++){
var str = testStrings[i];
document.body.innerHTML += str + ' => ' + isAnchor(str) + '<br>';
}
functionisAnchor(str){
return/^\<a.*\>.*\<\/a\>/i.test(str);
}
Solution 2:
Maybe this will point you in the right direction:
var stringOne = "<a href='./page'>Link</a>";
var stringTwo = "<a href='./page'>";
functionisA(str){
if (str.indexOf("href") > -1 && str.indexOf("</a>") > -1){
returntrue;
}else{
returnfalse;
}
}
console.log(isA(stringOne));
console.log(isA(stringTwo));
Post a Comment for "How To Check If A String Is An Anchor Tag?"