Catie
Catie

Reputation: 555

How to replace regex to pattern from string in JavaScript

I have this string: http://zrack-profile-a.comaihd.net/foobar.jpg which I want to convert to http://z-r.ac.zrack.net/profile.ac/foobar.jpg

So first I check whether the string input matches a regex:

regex = "^(https?)://(?!z-[mn])(zrack)([0-9a-zA-Z.-]+)(-a.comaihd).net(:?[0-9]{0,5})"

The code: input.match(regex) returns true. and so now I need to replace this regex with another pattern.

pattern = "$1://z-r.ac.zrack.net$5/$3.ac$6"

Then I do inputNew = input.replace(regex, pattern). However this does not change inputNew at all; inputNew == input. What am I doing wrong? Also the input string can be a variety of things, and that is why my regex is more complicated that needed for the above input string provided.

The following works perfectly in PHP.

Any help would be appreciated. Thanks!

Upvotes: 0

Views: 130

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95518

You need to do:

input = input.replace(regex, pattern);

String#replace(...) only performs the replacement and returns a new String instance; it does not modify the original string.

EDIT

Perhaps it might have to do with how you've defined your regular expression? It needs to be a literal that is bounded by / and not by ":

regex = /^(https?):\/\/(?!z-[mn])(zrack)([0-9a-zA-Z.-]+)(-a.comaihd).net(:?[0-9]{0,5})/;

You can also use the RegExp object:

var regex = new RegExp("^(https?)://(?!z-[mn])(zrack)([0-9a-zA-Z.-]+)(-a.comaihd).net(:?[0-9]{0,5})");

Upvotes: 2

rtcherry
rtcherry

Reputation: 4880

regex needs to be a regular expression literal

regex = /^(https?):\/\/(?!z-[mn])(zrack)([0-9a-zA-Z.-]+)(-a.comaihd).net(:?[0-9]{0,5})/

or you need to create a new RegExp object

inputNew = input.replace(new RegExp(regex), pattern);

You may want to make it case insensitive.

Also, your posted regex returns http://z-r.ac.zrack.net/-profile.ac$6/foobar.jpg, not http://z-r.ac.zrack.net/profile.ac/foobar.jpg.

Edit: Fixing typo.

Upvotes: 0

Related Questions