Dhia Eddine Farah
Dhia Eddine Farah

Reputation: 260

Javascript: Replace specific words in string

I like to change URL in function of the language so for that I tried this code:

var dec = {
  "agence": "agency",
  "conseil": "consulting",
  "partnaires": "partners",
  "a-propos": "about",
  "recherche": "search"
}
var url = window.location.href;
var urlRedirect = url.replace("/fr/", "/en/");
urlRedirect = urlRedirect.replace(!!) // how can I use the dec ?

For example if my URL like this:http://exemple.com/fr/agence

It should be like this:http://exemple.com/en/agency

Upvotes: 0

Views: 121

Answers (3)

Emeeus
Emeeus

Reputation: 5250

You could build a regex using Object.keys joining each key with | (or in a regex) then you could use it in the replace callback calling the value of dec.

var dec = {
  agence: "agency",
  conseil: "consulting",
  partnaires: "partners",
  "a-propos": "about",
  recherche: "search"
};
var url = "http://exemple.com/fr/agence/conseil/partnaires/a-propos/recherche";
var urlRedirect = url.replace("/fr/", "/en/");

var r = new RegExp(Object.keys(dec).join("|"), "gi");

urlRedirect = urlRedirect.replace(r, m =>dec[m]);

console.log(urlRedirect);

Upvotes: 1

Calvin Nunes
Calvin Nunes

Reputation: 6516

Iterate over the keys of the object using the for...in loop, then check if the key string is present in the URL, if yes, then replace() it with the value of that key.

See below, where I'm using a fake URL just for this example:

var dec = {
  "agence": "agency",
  "conseil": "consulting",
  "partnaires": "partners",
  "a-propos": "about",
  "recherche": "search",
  "fr":"en"
}

//var url =  window.location.href;
//let's fake a url here:
var url = "http://exemple.com/fr/agence";
console.log("entry URL: ", url)

for (var key in dec){
  if (url.indexOf(key) > -1){
    url = url.replace(key, dec[key])
  }
}

console.log("output URL: ", url);

Note: This will work, but if the URL has one of the words from dec in the main part of the URL, it will also change (for example: www.agence.com/fr will become www.agency.com/en) So, if you want just the path, the part after the / to change, use window.location.pathname, then replace just that part.

Upvotes: 3

Luca Kiebel
Luca Kiebel

Reputation: 10096

You have to get the string after the last slash and replace it by whatever dec[string] is:

var dec = {
  "agence": "agency",
  "conseil": "consulting",
  "partnaires": "partners",
  "a-propos": "about",
  "recherche": "search"
}
var url = "http://exemple.com/fr/agence"
var urlRedirect = url.replace("/fr/", "/en/");
var positionOfLastSlash = urlRedirect.lastIndexOf('/');
var lastPart = urlRedirect.substring(positionOfLastSlash + 1);
var firstPart = urlRedirect.substring(0, positionOfLastSlash+1);

if (lastPart in dec) {
  console.log(firstPart+dec[lastPart]);
}

Upvotes: 3

Related Questions