Home > front end >  Regex to get/replace strings in between two character sets in JavaScript
Regex to get/replace strings in between two character sets in JavaScript

Time:07-13

I have a string containing external url links like

.listView a.toggle::after { content: " "; background: url("/test/images/up_small.svg") center center no-repeat; }

I want to grab the text between the url tags like

/test/images/up_small.svg

I tried like

a.split(new RegExp("[^(url)\(\".*\"]"))

but it did not work.

How can I get the external url and if needed replace the same with something else? in JavaScript

CodePudding user response:

You can search using this regex with 2 capture groups:

(.* url\(")[^"] (".*)

And replace using $1http://example.com$2 where http://example.com is replacement.

RegEx Demo

Code:

var s = '.listView a.toggle::after { content: " "; background: url("/test/images/up_small.svg") center center no-repeat; }';

var r = s.replace(/(.* url\(")[^"] (".*)/, '$1http://example.com$2');

console.log(r);

  • Related