1

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>
4
  • Have you tried the getAttribute() method? Commented May 8, 2014 at 14:26
  • 2
    Oooh, so it's a string an not a real stylesheet, makes sense no, but how should we know what that even looks like, or how to get it ? Commented May 8, 2014 at 14:28
  • possible duplicate of jQuery getAttribute Commented May 8, 2014 at 14:29
  • that's not a stylesheet, that's a string :^) Commented May 8, 2014 at 14:32

3 Answers 3

4

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@Archer - Yes I did, got the tags a little mixed up.
3

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");

Comments

1

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>

5 Comments

@ejay, and why is that ?
@Ejay Time is your most precious asset, don't waste it!
Is it me or your comment is quite ironic?
@ejay, I was serious and ironic in a positive way! Enjoy your day;)
you too man. Chill out :) This comment/edit timing thing happens all the time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.