Skip to content

Instantly share code, notes, and snippets.

@ba0918
Last active May 2, 2017 03:41
Show Gist options
  • Save ba0918/c9eba7faffd2997da89fec7560217d6e to your computer and use it in GitHub Desktop.
Save ba0918/c9eba7faffd2997da89fec7560217d6e to your computer and use it in GitHub Desktop.
<!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>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
// 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