Regex replace a character inside
How do I wri开发者_StackOverflowte a regular expression in javascript that replaces everything with a certain chararacter inside "url()"?
Example string
"blabla url(hello;you);"
I want to replace the ";"-sign inside url() to something else to like
"blabla url(hello[]you);"
Hmm maybe something like this:
var result = "blabla url(hello;you)".replace(/url\(([^)]*)\)/, function(_, url) {
return "url(" + url.replace(/;/g, "[]") + ")";
});
I used two calls to ".replace()" which might not be necessary but it made it easier for me to think about. The outer one isolates the "url()" contents, and then the inner replace fixes the semicolons.
var str = "blabla url(hello;you;cutie);";
str = str.replace( /url\(([^)]+)\)/g, function(url){
return url.replace( /;/g, '[]' );
});
// "blabla url(hello[]you[]cutie);"
regEx seems a bit heavy. split-join is probably faster in most browsers.
var result = "blabla url(hello;you)".split(';').join('[]');
For regEx required I guess I'd do:
var result = "blabla url(hello;you)".replace(/;/,'[]');
精彩评论