Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function highlightText(params) {
- var p = {
- query: [],
- isAppend: true,
- searchAttr: 'xxxxx'
- };
- $.extend(p, params);
- var phrases = p.query,
- searchAttr = p.searchAttr,
- isAppend = p.isAppend;
- var source = this.html()
- .replace(/[\n|\t]+/gi, '')
- .replace(/\s+/gi, ' ')
- .replace(/> /gi, '>')
- .replace(/(\w)</gi, function (m, w) {
- return (w + " <");
- });
- phrases.forEach(function (str) {
- source = source.replace(makeRegexp(str), emulateSelection);
- });
- var result = {
- $el: this
- };
- if (isAppend) {
- result.$search = this.html(source).find("[search=" + searchAttr + "]");
- } else {
- var $source = $(source);
- result.$source = $source;
- result.$search = $source.find("[search=" + searchAttr + "]");
- }
- return result;
- function makeRegexp(s) {
- var space = '( )?(<span[^>]*>)?(</span[^>]*>)?( )?';
- var result = s.replace(/\s/gi, space);
- return new RegExp(space + result + space, "gi");
- }
- function emulateSelection(htmlPiece) {
- return htmlPiece
- .replace(/(?!=>)[^><]+(?=<)/g, wrapWords)
- .replace(/^[^><]+/, wrapWords)
- .replace(/[^><]+$/, wrapWords)
- .replace(/^[^><]+$/, wrapWords);
- }
- function wrapWords(plainPiece) {
- return '<span search="' + searchAttr + '">' + plainPiece + '</span>';
- }
- };
Add Comment
Please, Sign In to add comment