-3

I wrote a function in JavaScript, that replaces accents in a string to certain characters.

    function textToURL(str) {
    str = str.replace(/á/gi,'a');   
    str = str.replace(/é/gi,'e');   
    str = str.replace(/í/gi,'i');   
    str = str.replace(/ó/gi,'o');   
    str = str.replace(/ö/gi,'o');   
    str = str.replace(/ő/gi,'o');   
    str = str.replace(/ú/gi,'u');   
    str = str.replace(/ü/gi,'u');   
    str = str.replace(/ű/gi,'u');   
    str = str.replace(/ /gi,'-');   
    return str;
}

I'm sure there's a more clean and more simple way to write this code with arrays, or Regex, but how?

Thanks in advance.

Kobanric
  • 23
  • 3

2 Answers2

0

Something like this might work for you:

// define a translator map
var dict = {"á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", " ": "-"}

var str = "ápplé órángé"

var repl = str.replace(/[áéíóú ]/g, function($0) { return dict[$0]; });
//=> apple-orange
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You can use an associative array, then replace the key by his value

str = "áéíóöőúüű "

var myArray = {á:"a", é:"e", í:"i",ó:"o", ö:"o", ő:"o",ú:"u", ü:"u", ű:"u", " ":"-"}

var index;
for(var key in myArray){
    str = str.replace(key, myArray[key])
}

Here is the jsfiddle link to try it yourself : http://jsfiddle.net/7sdoh65a/1/