Efficiently replace all accented characters in a string??

Answer

ere is one way to do this:

function makeSortString(s){if(!makeSortString.translate_re) makeSortString.translate_re =/[öäüÖÄÜ]/g;var translate ={"ä":"a","ö":"o","ü":"u","Ä":"A","Ö":"O","Ü":"U"// probably more to come};return( s.replace(makeSortString.translate_re,function(match){return translate[match];}));}

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re =/[a-z]/g;

So, there is that option.

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString =(function(){var translate_re =/[öäüÖÄÜ]/g;returnfunction(s){var translate ={"ä":"a","ö":"o","ü":"u","Ä":"A","Ö":"O","Ü":"U"// probably more to come};return( s.replace(translate_re,function(match){return translate[match];}));}})();

Hopefully this is useful to you.


UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString =(function(){var translate_re =/[öäüÖÄÜ]/g;var translate ={"ä":"a","ö":"o","ü":"u","Ä":"A","Ö":"O","Ü":"U"// probably more to come};returnfunction(s){return( s.replace(translate_re,function(match){return translate[match];}));}})();

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---