is it possible to use regex in js to replace several different chars?

javascript string replace multiple occurrences
regex replace multiple characters c#
javascript replace multiple strings with one string
replace multiple characters java
replace multiple strings with multiple other strings javascript
replace repeated characters javascript
regex replace multiple characters python
javascript chain replace

I need to replace all accented char in a string by it's unaccented version, for sorting. I found how to match the accented ones, but is it possible to use a regex to replace each one? I mean:

var re = /ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ/g;
var str = "ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ";
var newstr = str.replace(re, 'M');
console.log(newstr);

this prints 'M' but I need :'uUuUaaaeeeiiiooouuuAAAEEEIIIOOOUUnN'

Is this possible? thanks

You need to use character classes.

var re = /[ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ]/g;

Then, you can pass a function as a second argument to the replace function. This function shall contain the conversion logic. A simple way would be to use a conversion map.

E.g.

var re = /[ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ]/g;

//incomplete but you get the idea
var conversionMap = {
    'ù': 'u',
    'Ù': 'U',
    'ü': 'u',
    'Ü': 'U',
    'ä': 'a'
};

"ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ".replace(re, function (c) {
    return conversionMap[c] || c;
}); //uUuUaàáëèéïìíöòóuuúÄÀÁËÈÉÏÌÍÖÒÓUÚñÑ

FIDDLE

How can I replace multiple characters in a string?, . lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replace () method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Note: If you are replacing a value (and not a regular expression ), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g

This is fairly verbose, in order to be readable. (Well, to each their own, anyway.)

var deaccentuate = (function() {
  var conversion =
      { 'a' : /[äàá]/g
      , 'e' : /[ëèé]/g
      , 'i' : /[ïìí]/g
      , 'o' : /[öòó]/g
      , 'u' : /[üùú]/g
      , 'n' : /ñ/g
      , 'A' : /[ÄÀÁ]/g
      , 'E' : /[ËÈÉ]/g
      , 'I' : /[ÏÌÍ]/g
      , 'O' : /[ÖÒÓ]/g
      , 'U' : /[ÜÙÚ]/g
      , 'N' : /Ñ/g
      }

  return function(str) {
    return Object.keys(conversion).reduce(function(str, c) {
      return str.replace(conversion[c], c)
    }, str)
  }
}())

Usage: (http://jsbin.com/UFEbuho/1/)

var input = "ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ"

console.log(deaccentuate(input))

The idea is to loop over the keys of the conversion table and replace anything that matches the pattern of that key to the key itself. This is certainly not the most efficient way to do this, but unless the input strings are fairly long it shouldn't matter much.

String replaceAll() example - How to replace all , () in order, so if the first new contains the following old , the first new is also replaced. To interpret literally, use a backslash. [abc] is a character class that means "any character from a,b or c" (a characer class may use ranges, eg [a-d] = [abcd] ) Debug logs

http://jsfiddle.net/Victornpb/YPtaN/4

var deaccentuate = (function(){

    var accent = "ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ",
        latin  = "uUuUaaaeeeiiiooouuuAAAEEEIIIOOOUUnN".split("");

    var re = new RegExp("["+accent+"]", "g");

    return function(str){
        return str.replace(re, function(c){
            return latin[accent.indexOf(c)]; }
        );
    } 
})();

deaccentuate("Olá, como estás?"); //Ola, como estas?
Benchmark

I realized a benchmark test with a 2KB text and my function was faster than other answers, reaching 59000 Ops/sec

http://jsperf.com/deaccentuate

How to Change Multiple Words in Microsoft Word, How do you replace a single character in a string JavaScript? Substitutions are language elements that are recognized only within replacement patterns. They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters.

I can't think about an easier way to efficiently remove all diacritics from a string than using this amazing solution.

See it in action:

var str = "ùÙüÜäàáëèéïìíöòóüùúÄÀÁËÈÉÏÌÍÖÒÓÜÚñÑ";

var str_norm = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
console.log(str_norm);

Replace strings in Python (replace, translate, re.sub, re.subn), all the occurrence you can use the global ( g ) modifier. String: You can use Regex.Replace for simple replacements by using a string argument. For complex replacements, use MatchEvaluator. UpperFirst: In Regex.Replace, we use the delegate (Match match) syntax for a method that alters strings to have an uppercase first letter. Tip: Delegate methods are methods you can use as variables and parameters

How to Replace Character Inside a String in JavaScript, Example 1: This example uses the RegExp to replace the strings according to the object using the replace() method. filter_none. edit close. play_arrow. link javascript,regex The best place I have found for the exec method is Eloquent Javascript Chapter 9: "Regular expressions also have an exec (execute) method that will return null if no match was found and return an object with information about the match otherwise. An object returned from exec has an index

JavaScript, Replacing strings in JavaScript is a fairly common task, but there are some nuances that To replace all occurrences, you'll want to use the regex flavored version of replace() . We're dealing with regex now, so don't forget to escape characters that have For example, replacing multiple words at once. A regular expression is a sequence of characters used for parsing and manipulating strings. and it’s better to use several smaller regex instead. Javascript style regex, but useful for

JavaScript String Replace Magic / Coder's Block, I receive a string with a lot of characters that I don't need and I am trying to remove them and replace them with characters that I am able to work with. My current  The point of this function is to perform a replace all using the javascript replace function via a regular expression for speed, and at the same time eliminate the side effects that occur when regular expression special characters are inadvertently present in either the search or replace string.

Comments
  • what about ^ âêîôûÂÊÎÔÛ ?
  • Thanks, that's part of it, now i get one 'm' for each char! Great! Now this 'logic' would be an other regex? I mean if i build this in javaScript with for()s if()s and switch()s there is no good to use regex in first place right? Sorry if I'm dumb about this.
  • Ahhh!! great now I get the idea.Thanks!
  • @v.k. replace doesn't modify the original string, it returns a new one. Strings are immutable. jsfiddle.net/PT6Xc/3
  • I did the hash map and modified to a cached version jsfiddle.net/Victornpb/PT6Xc/7
  • @Vitim.us, Have a look at mine in the link above your comment. You can actually cache the replace callback as well and you do not need the logical || operator anymore.
  • I liked this, thanks. Also it brought my attention to reduce(). You think this has performance differences with the above solution proposed by @plalx?
  • @v.k. The reduce part will not have much impact since looping over a few items is quite fast, however performing 12 replace operations will certainly have a negative impact. However, it will not be noticeable on small inputs, but you know, once the helper function is written, it's still one line to perform the replace operation independently of the implementation...
  • @plalx is absolutely right. The discussion re: performance really is moot since your input probably isn't large enough for it to make a difference and/or the implementation can change without changing the interface.
  • Shorter, but quite inefficient.
  • @Vitim.us thanks, it works, but the other version is indeed faster.
  • @Vitim.us :) great! I didn't even know jsperf. Love it thanks for that also. The diff with @ plalx was minimal.
  • Yeah not much difference, but I just wanted to know if it was really "inefficient" as commented, seems to not be the case. Also have a small footprint than the replace object.
  • At the end of the day, you are all right, and have helped me a lot. All answers are correct, I can only mark one as correct though... But i can thanks you all...