Skip to content

Instantly share code, notes, and snippets.

@EloB
Created June 7, 2015 14:54
Show Gist options
  • Save EloB/828a2de9f1f9b37b21e3 to your computer and use it in GitHub Desktop.
Save EloB/828a2de9f1f9b37b21e3 to your computer and use it in GitHub Desktop.
Why is this regexp slow?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Slow regexp</title>
</head>
<body>
<script>
function convertHtmlToText(html) {
el.innerHTML = html;
return el.textContent || el.innerText;
}
var el = document.createElement('div'),
a = convertHtmlToText('a'),
b = convertHtmlToText('b'),
space = convertHtmlToText(' '),
nonBreakingSpace = convertHtmlToText('&nbsp;'),
slowRegExpTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
spaces,
text;
alert('Open console');
console.log(slowRegExpTrim);
setTimeout(function() {
for(var tests = 0; tests < 32; tests++) {
spaces = '';
for(var i = tests; i; i--) spaces += space + nonBreakingSpace;
text = a + spaces + b;
console.log(tests, text);
console.time('Slow regexp');
text.replace(slowRegExpTrim, '');
console.timeEnd('Slow regexp');
}
}, 5000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment