I need to validate the incoming string for text <script
.
string a = "This is a simple <script> string";
Now, I need to write a regular expression that will tell me whether this string contains a <script>
tag or not.
I ended up writing something like: <* ?script.* ?>
But the challenge is, Incoming string may contain script in following ways,
string a = "This is a simple <script> string";
string a = "This is a simple < script> string";
string a = "This is a simple <javascript></javascript> string";
string a = "This is a simple <script type=text/javascript> string";
Hence the regular expression should check for starting <
tag and then it should check for script
.
You can use native Javascript to do this! External tag can be loaded dynamically instead of inline. Then the code will be inserted between opening and closing tags. It works for me. is there some way to use this method to select script tags that have a specific type attribute?
Save the script file with a .js extension, and then refer to it using the src attribute in the <script> tag. Note: The external script file cannot contain the <script> tag. Note: Point to the external script file exactly where you would have written the script.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
/<script[\s\S]*?>[\s\S]*?<\/script>/gi
@bodhizero’s accepted answer of <[^>]*script
incorrectly returns true
under the following conditions:
// Not a proper script tag.
const a = "This is a simple < script> string";
// Space added before "img", otherwise the entire tag fails to render here.
const a = "This is a simple < img src='//example.com/script.jpg'> string";
// Picks up "nonsense code" just because a '<' character happens to precede a 'script' string somewhere along the way.
const a = "This is a simple for(i=0;i<5;i++){alert('script')} string";
Here is an excellent resource for building and testing regular expressions.
Try this:
/(<|%3C)script[\s\S]*?(>|%3E)[\s\S]*?(<|%3C)(\/|%2F)script[\s\S]*?(>|%3E)/gi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With