user1832665
user1832665

Reputation:

javascript replace url

Can someone write a javascript code that replace

"www.mydomain.com/happy_new_year/yeah-00-14-jj-78-aaa1.html"

to

"www.mydomain.com/happy_new_year/ohoh-11-22-33-44-aaa1.html"

Note that the folder in this case /happy_new_year/ will stay the same.

But we don't know the exact folder name, could be something else, and sometimes no folder is present, and don't need to change.

Replace every character after that except the last 4 characters before .html

There is a pattern of how many slashes '-' could be useful.

Thanks

Upvotes: 0

Views: 234

Answers (1)

akuhn
akuhn

Reputation: 27793

Use a regular expression

url.replace(/[^\/]*(....\.html)$/,new_name + "$1");

The $ sign tells the match to start from the end of the string, it then captures .html and the next four characters in a group, and eventually matches as many characters that are not a / as possible. The $1 in the replacement expands to the captured group.

Upvotes: 2

Related Questions