Skip to content

Instantly share code, notes, and snippets.

@codfish
Last active December 26, 2015 13:59
Embed
What would you like to do?
// You are looking for the /.../s modifier, also known as the dotall modifier. It forces the dot . to also match newlines, which it does not do by default.
// The bad news is that it does not exist in Javascript. The good news is that you can work around it by using a character class (e.g. \s) and its negation (\S) together, like this:
var htmlStringWithScriptTags = "sdf <script>test fsajkdfn</script> a sdasda <script> sdfsdfsdf \n \
sdfsdfsd </script> sjkndfjkasnd <script> sdfsdfsdf \n \
sdfsdfsd </script>sjkndfjkasnd <script> sdfsdfsdf \n \
sdfsdfsd </script>";
// incorrect
htmlStringWithScriptTags.replace(/<script.*?<\/script>/g, '');
/* outputs:
"sdf a sdasda <script> sdfsdfsdf
sdfsdfsd </script> sjkndfjkasnd <script> sdfsdfsdf
sdfsdfsd </script>sjkndfjkasnd <script> sdfsdfsdf
sdfsdfsd </script>"
*/
// correct
htmlStringWithScriptTags.replace(/<script[\s\S]*?<\/script>/g, '');
// outputs: "sdf a sdasda sjkndfjkasnd sjkndfjkasnd "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment