Reputation: 28
I am trying write a function that can swap out unicode characters in a string for non unicode ASCII characters, the problem being unicode hyphens and quotes are not being read when uploading a string that contains them.
I would like the function to have an object with key value pairs (so that it can be updated with more unicode quotes or hyphens that may cause problems in the future), the key of the object being the ASCII quote "
and the value being a collection of unicode quotes ”
to swap out of the string.
function replaceUnicode(string) {
var dictionary = {
'"': '"”"”',
'-': '-﹣'
}
}
I know you can use a regular expression to swap out unicode characters in a string but I'd like to use this object as a dictionary of selected unicode characters instead. What I am asking is if you passed in a string that contained unicode quotes that matched the values of of the dictionary, how could you swap those quotes for the dictionary object key value?
Upvotes: 0
Views: 328
Reputation: 2815
You can use the dictionary, but you'll still need to do the replacement with regex to find the matches.
Something like this should work:
function replaceUnicode(s) {
var dictionary = {
'"': '"”"”',
'-': '-﹣'
}
for(var key in dictionary) {
var re = new RegExp(key,"g");
s = s.replace(re,dictionary[key])
}
return s
}
var str = 'hello "world" - how are - you';
console.log(replaceUnicode(str))
You can see it working here: https://jsfiddle.net/krpxu0gL/
Hope that helps!
Upvotes: 1