I am new to regular expressions. Can anyone suggest me the equivalent regular expression for below strings. I need to validate these in input text-box.
"Start<b>Middle</b>End"
or
"Start<b>End</b>"
or
"<b>Start</b>End"
or
"StartMiddleEnd"
I am new to regular expressions. Can anyone suggest me the equivalent regular expression for below strings. I need to validate these in input text-box.
"Start<b>Middle</b>End"
or
"Start<b>End</b>"
or
"<b>Start</b>End"
or
"StartMiddleEnd"
Really you should use the DOM for this.
First convert the strings into DOM objects and once you have done that check whether it contains a b
tag:
function hasBTag(html) {
var parser = new DOMParser();
var node = parser.parseFromString(html, "text/html");
var allNodes = node.getElementsByTagName('*');
for (var i = -1, l = allNodes.length; ++i < l;) {
if (allNodes[i].nodeName === 'B' ) {
return true;
}
}
return false;
}
(function() {
var html = [
'"Start<b>Middle</b>End"',
'"Start<b>End</b>"',
'"<b>Start</b>End"',
'"StartMiddleEnd"'
];
for (var i = 0, l = html.length; i < l; i++) {
if (hasBTag(html[i])) console.log(html[i] + ' haz b tag');
}
}());
Le demo: http://jsfiddle.net/mZu7Z/
Trying to parse HTML using regex is almost always a terrible idea.
dude you are not that clear. just to check if bold tag is there or not you dont need regular expression. If you want to check any pattern rather than just a fixed text then regular expressions mainly come into picture. Assuming you dont want to replace but only test wether bold tag is present on not just use indexOf.
var strToTest = "Hi, my name is <b>Ankur</b>";
if(strToTest.indexOf("<b>")!=-1 || strToTest.indexOf("</b>")!=-1)
{
console.log("String includes bold tag");
}
Few people say that you need to escape <,> and /. however in this scenario it is not needed.
If you want to use regular expression to check both start and end bold tag then use this
/\</?b>/gi
This tests for both and