Codler
Codler

Reputation: 11256

Regex replace a character inside

How do I write 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);"

Upvotes: 0

Views: 527

Answers (3)

Erik  Reppen
Erik Reppen

Reputation: 4635

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(/;/,'[]');

Upvotes: 0

Pointy
Pointy

Reputation: 413682

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.

Upvotes: 3

Phrogz
Phrogz

Reputation: 303136

var str = "blabla url(hello;you;cutie);";
str = str.replace( /url\(([^)]+)\)/g, function(url){
  return url.replace( /;/g, '[]' );
});
// "blabla url(hello[]you[]cutie);"

Upvotes: 1

Related Questions