What would be the easiest way with regex to extract the href
string containing a stylesheet link and save it to a variable in JavaScript?
The stylesheet is a string and not a real stylesheet link. It's intended to be inserted with Javascript after the page loads.
EDIT:
<script>
// Loading stylesheet just before body closes
$(function() {
var stylesheet = '<link href="/Static/css/compiled/styles.css" rel="stylesheet"/>';
var stylesheetHref = ""; // WANT TO SET THIS!!
if (document.createStyleSheet) {
document.createStyleSheet(stylesheetHref);
} else {
$("head").append(stylesheet));
}
});
</script>
Why not create elements the proper way and just start out with the href in a variable ?
$(function () {
var href = '/Static/css/compiled/styles.css';
var stylesheet = $('<link />', {rel: 'stylesheet', href: href});
$("head").append(stylesheet);
});
If you have a stylesheet link in string format then this will get you the href value, very easily without regex...
var link = '<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/stackoverflow/all.css" />';
var href = $(link).attr("href");
Try this:
<script>
// Loading stylesheet just before body closes
$(function() {
var stylesheet = '<link href="/Static/css/compiled/styles.css" rel="stylesheet"/>';
var stylesheetHref = stylesheet.replace(/.*href="(.*?)".*/i, "$1");
if (document.createStyleSheet) {
document.createStyleSheet(stylesheetHref);
} else {
$("head").append(stylesheet));
}
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.