Last active
March 4, 2022 13:57
-
-
Save codeeshop-oc/53c6c8884f795b578f38cfa31e4e557a to your computer and use it in GitHub Desktop.
Get Script Tag / Attributes Using JavaScript String Prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
In case you want solution using NPM Package | |
### https://www.npmjs.com/package/get-script-tag | |
*/ | |
// String to find script tags from | |
let html = `<p>You have the Script Tags <script type=\"text/javascript\" async=\"async\" src=\"//web.webformscr.com/apps/fc3/build/default-handler.js\" sp-form-id=\"YOUR_ID\"></script></p>` | |
// Individual Script Tag with Index | |
String.prototype.getScriptTag = function() { | |
let tags = this.getScriptTags() | |
return tags != null && tags.length ? tags[0] : '' | |
}; | |
// Array of All Script Tags | |
String.prototype.getScriptTags = function() { | |
let tags = this.match(/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>/g) | |
return tags != null ? tags : [] | |
}; | |
// Fetching Script Tag Attributes from All Script Tags | |
String.prototype.getScriptAttributes = function() { | |
let attrCombination = this.replace(/['"]+|<script |><\/script>|<\/script>/g, '').split(' ') | |
const opts = {} | |
for(let i = 0; i <attrCombination.length; i++) { | |
if(attrCombination[i].indexOf('=') > 0) { | |
let attr = attrCombination[i].split('=') | |
opts[attr[0]] = attr[1] | |
} | |
} | |
return opts | |
}; | |
/* Usage Example */ | |
const scripts = html.getScriptTags() | |
console.log(html.getScriptTag()) | |
for (var i = scripts.length - 1; i >= 0; i--) { | |
console.log(scripts[i].getScriptAttributes()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment