Skip to content

Instantly share code, notes, and snippets.

@venil7
Last active January 2, 2016 08:09
Show Gist options
  • Save venil7/8275016 to your computer and use it in GitHub Desktop.
Save venil7/8275016 to your computer and use it in GitHub Desktop.
emphasis function js
var em = function(str, pattern, el) {
if (!(str && pattern)) return "";
pattern = pattern.toString().replace((/[^a-zA-Z1-9 ]/ig), "").split(" ").reduce(function(prev, curr){
if(curr){
prev.push(curr);
}
return prev;
},[]).join("|");
el = el || "em";
var ret = [],
match,
regex = new RegExp(pattern, 'ig');
while(match = regex.exec(str)) {
var index = match.index,
before = str.substring(0, index),
wrap = "<"+el+">"+match[0]+"</"+el+">";
str = str.substr(regex.lastIndex);
ret.push(before, wrap);
regex.lastIndex = 0;
}
ret.push(str);
return ret.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment