Replace append text before last occurrence of the string

Viewed 55

I am trying to construct a RegExp to append text before the last occurrence of the string, but in the current approach, the replaced .html part is lost. Can you please suggest how can it be fixed?

const URL = 'www.website.com/path/fileName.html'
const urlPrefix = '.prefix1.prefix2'
const newURL = URL.replace(/.html(^)*$/, `${urlPrefix}$1`)

// Expected output www.website.com/path/fileName.prefix1.prefix2.html
console.log(newURL)

3 Answers

Here is your answer bro. You can add as many prefixes in this, just you need to push it in the array. First, we split the URL into an array of strings. Then, we pop out the last index string from that array that will be the initial last prefix. Then, we can push as many prefixes into the array. Finally, we will push the initial last prefix to the same array and join the array of strings with Dot(.) and we will get the desired output string.

const URL = "www.website.com/path/fileName.html";
const arr = URL.split("."); // output: ["www","website","com/path/fileName","html"]

const lastprefix = arr.pop(); // output: html

arr.push("prefix1"); // output: ["www","website","com/path/fileName","prefix1"]
arr.push("prefix2"); // output: ["www","website","com/path/fileName","prefix1","prefix2"]
arr.push(lastprefix); // output: ["www","website","com/path/fileName","prefix1","prefix2","html"]

const newURL = arr.join("."); // output: www.website.com/path/fileName.prefix1.prefix2.html

// Expected output www.website.com/path/fileName.prefix1.prefix2.html
console.log(newURL)

Just replace the .html part too.

const URL = 'www.website.com/path/fileName.html'
const urlPrefix = '.prefix1.prefix2'
const newURL = URL.replace(/.html(^)*$/, `${urlPrefix}$1.html`)

// Expected output www.website.com/path/fileName.prefix1.prefix2.html
console.log(newURL)

The (^)* is redundant in your regex because it matches start of string zero or more times, which is rather meaningless.

The backreference to whole match is $&, not $1, the $1 is empty in your case since (^)* simply captures an empty string.

You can use

URL.replace(/\.html$/, `${urlPrefix}$&`)

Note the escaped dot, else, . matches any char but line break chars.

See a JavaScript demo:

const URL = 'www.website.com/path/fileName.html'
const urlPrefix = '.prefix1.prefix2'
const newURL = URL.replace(/\.html$/, `${urlPrefix}$&`)
console.log(newURL)
// => www.website.com/path/fileName.prefix1.prefix2.html

Related