Last active
January 2, 2016 08:09
-
-
Save venil7/8275016 to your computer and use it in GitHub Desktop.
emphasis function js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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