Reputation: 470
I need to replace special characters like
in a string. what is the best way to do it?
Upvotes: 1
Views: 479
Reputation: 20141
Consider encodeURIComponent (and the associated decode).
The example given on that w3schools page:
var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
document.write(encodeURIComponent(uri));
Output:
http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
Note the å in the middle becomes %C3%A5
.
If you don't mind * @ - _ + . /
not being encoded, there is also escape() (and unescape()).
EDIT in light of 'human-readable' requirement:
Be careful that you cover all the characters that might come up by doing an 'oe' type replacement, and that you never attempt to convert these 'readable' strings back to their original form, or you will corrupt things in the transformation. This is the point of the escape and unescape methods.
Consider applying escape/unescape after your own transform to catch any remaining unexpected characters.
Upvotes: 2
Reputation: 470
After googling i couldn't find anything suitable. So i ended up writing my own.
normalize = (s) ->
mapping =
'ä': 'ae'
'ö': 'oe'
'ü': 'ue'
'&': 'and'
'é': 'e'
'ë': 'e'
'ï': 'i'
'è': 'e'
'à': 'a'
'ù': 'u'
'ç': 'c'
"'": ''
'´': ''
r = new RegExp(Object.keys(mapping).join('|'), 'g')
s.replace(r, (s)->
mapping[s]
)
Upvotes: 2