Last active
May 2, 2017 03:41
-
-
Save ba0918/c9eba7faffd2997da89fec7560217d6e to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>test</title> | |
<style>.highlight-link { background-color: yellow; }</style> | |
</head> | |
<body> | |
<h2>Sample</h2> | |
<p id="root"> | |
http://google.co.jp<br> | |
</p> | |
<script src="./simple-link-decorator.min.js"></script> | |
<script> | |
var elm = document.querySelector('#root'); | |
elm.innerHTML = SimpleLinkDecorator.decorate(elm.innerHTML, {class: 'highlight-link'}); | |
</script> | |
</body> | |
</html> |
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
// export to window.SimpleLinkDecorator | |
const PATTERN = /((http|https):)?(?:\/\/)([-\+;:&@=\$,\.\w_]+)(\/[-\+~%\/\.\w_]*)?(\?[-\+=&;%@\w_]*)?(#[\w]*)?/g; | |
export function decorate(text, option = {}) { | |
const attributes = createKeyValuePairs(option).join(''); | |
const callback = (option.callback && typeof option.callback === 'function') ? option.callback : null; | |
return text.replace(PATTERN, (match) => { | |
return callback ? callback(match) : `<a href="${match}"${attributes}>${match}</a>`; | |
}); | |
} | |
function createKeyValuePairs(attributes) { | |
const result = []; | |
for (const key in attributes) { | |
if (key !== 'callback') { | |
result.push(` ${key}="${attributes[key]}"`); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment