how to replace url in css using regexp (javascript)
var text = '#anything {behavior:url("csshover.htc");}'; //iam using开发者_如何学Go " 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 ?
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('#')");
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* )
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.
精彩评论