Reputation: 930
I am attempting to use regexes in jQuery, and I am running into some problems. This is the string that I am operating on:
NSLog(@"It works!");
I want the regex to select everything between the @" and the ", inclusive. This regex works just fine in Reggy, but when put in my JavaScript, does not work:
@".*"
My jQuery code is as follows in this section (is single-quotes the issue, perhaps?):
var regex='@".*"';
$(".syntaxhighlight").highlight(regex,'string');
I know the issue is not the highlight() function, because this works just fine:
$(".syntaxhighlight").highlight('nil','string');
So, how do I get this regex working properly?
Upvotes: 2
Views: 96
Reputation: 173562
The highlight()
feature uses String.indexOf()
internally, which doesn't support regular expression objects.
However, it can be rewritten like so:
$.fn.extend({
highlight: function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var res;
while (res = pat.exec(node.data)) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(res.index);
var endbit = middlebit.splitText(res[0].length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat ? this.each(function() {
innerHighlight(this, pat);
}) : this;
}
});
Upvotes: 3
Reputation: 7596
Yes. Regex are defined in javascript in this way:
/Your Expression/flags
In your case:
var regex = /@".*?"/;
Upvotes: 3