2
var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";

result

#anything {
    behavior:url("#");
}

#anything {
    background:transparent url('#') no-repeat;
}

#anything {
    background-image:url('#');
}

How can i do that ?

0

3 Answers 3

4

Replace # below with $2 if you want to get the URL with single quotes.

var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += ".regleft {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";
text = text.replace(/url\((['"])(.+?)\1\)/g, "url('#')");
Sign up to request clarification or add additional context in comments.

3 Comments

text = text.replace(/url\((['"])(.+?)\1\)/g, "url('#')"); Thanks,This code helped me in my project.
Your regex wipes out the url() part so you're just left with '#'.
I'd suggest adding ? after ['"] so you also get urls without quotes. 'url(http://blabla.com)'.replace(/url\((['"]?)(.+?)\1\)/g, "$2");
1

For others who come here looking for a general solution that preserves both whitespace and quotes:

//Test data
var css = 'one url(two) url(\'three\') url("four")  url  (  five  )';

css = css.replace(

    // Regex
    /(url\W*\(\W*['"]?\W*)(.*?)(\W*['"]?\W*\))/g,

    // Replacement string
    '$1*$2*$3'

);

console.log(css);

outputs

one url(*two*) url('*three*') url("*four*")  url  (  *five*  ) 

Comments

0

Example: http://jsfiddle.net/GcsLQ/2/

var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";


text = text.replace(/url\([^)]+\)/g, 'url("#")');

If you want the space formatting as well, do this:

Example: http://jsfiddle.net/GcsLQ/3/

var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";


text = text.replace(/url\([^)]+\)/g, 'url("#")')
    .replace(/{/g,'{\n\t')
    .replace(/}/g,'\n}\n');

EDIT: Added quotes to the replaced URL.

Comments

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.