Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codfish
Last active December 26, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codfish/7161875 to your computer and use it in GitHub Desktop.
Save codfish/7161875 to your computer and use it in GitHub Desktop.
// 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