javascript - Selecting All Text After A "#" Symbol With Regular Expressions -



javascript - Selecting All Text After A "#" Symbol With Regular Expressions -

i've got bit of jquery javascript , regex mixed in:

$(function() { var regexp = new regexp("\\b(" + "hashtag" + ")\\b", "gm"); var boxlink = "<a class='taglink' onclick='tagbox()'>$1</a>" var html = $('body').html(); $('body').html(html.replace(regexp, boxlink)); }); function tagbox() { alert("it works!") };

basically applies $1 everywhere word "hashtag" appears. tagbox brings alert says works. simple enough. alter i'd create 1 won't jet select word "hashtag", words "#" symbols before them.

how can accomplish , work script above?

thanks in advance!

first of all, $('body').html(html) bad idea. you'll recreate dom, , event listeners bound nodes within old construction no longer function. traversing dom node node improve idea. should trick:

// douglas crockford's walkthedom function walkthedom(node, func) { func(node); node = node.firstchild; while (node) { walkthedom(node, func); node = node.nextsibling; } } function esc(text) { homecoming text.replace(/[&<>"'`]/g, function (chr) { homecoming '&#' + chr.charcodeat(0) + ';' }) } walkthedom(document.body, function (node) { if (node.nodetype === 3) { var html = '' // indexes contain hashtags; odd indexes contain // text appears between 1 hashtag , next. // // > 'this post tagged #javascript , #jquery'.split(/(#\w+)/) // ["this post tagged ", "#javascript", " , ", "#jquery", ""] // // text must escaped before beingness inserted via `.html()`. $.each(node.textcontent.split(/(#\w+)/), function (idx, text) { html += idx % 2 ? esc(text) : '<a class="taglink">' + esc(text) + '</a>' }) $(node).parent().html(html) } })

this code untested, , no uncertainty has bugs, i've convinced problem more hard may have appeared @ first.

javascript jquery regex

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -