Arkana
Arkana

Reputation: 2889

Replacing dynamic content jQuery/javascript

I need to do a dynamic replace in a string with jQuery. I have read about using wildcards in selectors, but I want it in a string.

Considering this HTML:

<style type="text/css">@import url('css/another.css');</style>
<style type="text/css">@import url('css/stylesMQ.css');</style>

And I have this function in jQuery:

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "400MQ.css");
        });
    } else if ((width >= 701) && (width < 900)) {
        $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "800MQ.css");
        });         
    } else {
       $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "MQ.css");
        });         
    }
}

This function is part of an entire jQuery that changes an @imported css depending of screen size.


ERROR

It works, but when I start playing with the screen size I get something like:

@import url('css/styles800800800800400400400400400400400400400400MQ.css');

I can't figure how can I tell jQuery to replace also the number.
I suppose that I need something like:

.replace("styles*MQ.css", "styles400MQ.css");

TIPS:

Upvotes: 0

Views: 1004

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388436

Instead of .replace("MQ.css", "MQ.css"); try something like

.replace(/\d*MQ\.css/, "MQ.css");
.replace(/\d*MQ\.css/, "400MQ.css");

Upvotes: 4

Edorka
Edorka

Reputation: 1811

I would use

$('style:contains("MQ")').text(function (pos, value) {
        return value.replace(/styles(400|)MQ\.css/, "styles800MQ.css");
});

same solution changing the expected expression (400, 800, '')

Upvotes: 0

Ashish
Ashish

Reputation: 48

$('style:contains("MQ")').text(function () {
    return $(this).text().split('/')[0]+"/400MQ.css";
});

Upvotes: 0

Related Questions