In comp.lang.javascript message <
[email protected]>, Tue,
4 Aug 2009 20:47:26 said:
Dr said:
jeanph01 posted:
How to do the same thing in javascript as this xsl function :
translate(@name,"àâÂ","aaa")
The only thing i can think of is a chain of replace.
ex:
chain.replace("à","a").replace("â","a").replace("Â","a");
For the general case,
Arr = []
for (J=0 ; J<65536 ; J++) Arr[J] = String.fromCharCode(J)
Arr[233] = "E" // replace é with E
Arr[0xFC] = "U" // replace ü with U
S1 = "foréign stüff"
S2 = ""
for (J=0 ; J<S1.length ; J++) S2 += Arr[S1.charCodeAt(J)]
Every character is unchanged in the copying, except for characters which
have been changed in the array Arr.
There is no need for this error-prone, inefficient approach. Where
String.fromCharCode() and String.prototype.charCodeAt(), or Array
initializers, are supported, String.prototype.replace() is supported
and can take a RegExp object reference as first argument. Cf. kangax's
solution.
Evidently you have, as usual, not been thinking. In the general case, a
considerable number of different characters will each need to be
replaced by some other character, and those other characters will not
all be the same. That could be done by a chain of RegExps, one for each
of the replacement characters, which would be at best inelegant. Or it
could be done with a single RegExp using a complicated function to do
the detail.
The OP wished to replace a variety of accented letters A, in both cases,
with lower-case a. ISTM very probable that he will want to do likewise
with all the other accented letters that might appear; perhaps more than
are in any one natural language.
Kangax's solution is of course good for the question as asked.