So as the question states, i’m trying to build a small helper function that will catch and fix special characters, I wasn’t sure where to go with it so opted for an object containing the characters, a check to see if it’s included and if so replace the character in the string with the appropriate object entry.
Im now however getting stuck, i’ve got the object and the check to see if it is in fact included. I just don’t know how to target the piece of the string, and then replace it. I tried using includes and replace but it doesn’t seem to work.
Here’s my code:
export function fixEncoding(str) {
const specialChars = {
"À": "À ",
"Á": "Á",
"Â": "Â",
"Ã": "Ã",
"Ä": "Ä",
"Å": "Å",
"à": "à",
"á": "á",
"â": "â",
"ã": "ã",
"ä": "ä",
"å": "å",
"Æ": "Æ",
"æ": "æ",
"ß": "ß",
"Ç": "Ç",
"ç": "ç",
"È": "È",
"É": "É",
"Ê": "Ê",
"Ë": "Ë",
"è": "è",
"é": "é",
"ê": "ê",
"ë": "ë",
"ƒ": "ƒ",
"Ì": "Ì",
"Í": "Í",
"Î": "Î",
"Ï": "Ï",
"ì": "ì",
"í": "í",
"î": "î",
"ï": "ï",
"Ñ": "Ñ",
"ñ": "ñ",
"Ò": "Ò",
"Ó": "Ó",
"Ô": "Ô",
"Õ": "Õ",
"Ö": "Ö",
"ò": "ò",
"ó": "ó",
"ô": "ô",
"õ": "õ",
"ö": "ö",
"Ø": "Ø",
"ø": "ø",
"Œ": "Œ",
"œ": "œ",
"Š": "Š",
"š": "š",
"Ù": "Ù",
"Ú": "Ú",
"Û": "Û",
"Ü": "Ü",
"ù": "ù",
"ú": "ú",
"û": "û",
"ü": "ü",
"µ": "µ",
"×": "×",
"Ý": "Ý",
"Ÿ": "Ÿ",
"ý": "ý",
"ÿ": "ÿ",
"°": "°",
"†": "†",
"‡": "‡",
"<": "<",
">": ">",
"±": "±",
"«": "«",
"»": "»",
"¿": "¿",
"¡": "¡",
"·": "·",
"•": "•",
"™": "™",
"©": "©",
"®": "®",
"§": "§",
"¶": "¶",
"'": "'",
""": '"',
};
let isinclude = (str, obj) => (
(str = str.replace("/", "")),
Object.keys(obj).reduce((a, v) => a || str.includes(v), false)
);
console.log(isinclude(str, specialChars));
for (let i = 0; i < specialChars.length; i++) {
if (str.includes(specialChars[str])) {
console.log(str);
const newStr = str.replace(`${i}`, specialChars[str]);
return newStr;
} else return str;
}
// return str.replace(/'+/g, "'").replace(/"+/g, '"');
}
3
Answers
You don’t need an object for something as simple as character replacement.
First,
specialChars
is an object, not an array, so you usespecialChars.length
, Also, your replacement logic inside the loop isn’t correctly set up to handle the replacement for all occurrences of each character.If it’s HTML Entities you need to replace you can do so in just one swoop…
Output: À Á Â Ã Ä Å à á â ã ä å