Reputation: 2085
I have a string with accent character with an extra backward slash.
const name = "V\\u00E1ci"
console.log(name); // prints "V\u00E1ci"
I am finding it hard to display it properly, tried various combination of string replace, searched web. but no luck :(
Is there any way I can convert above name to display properly ignoring the first extra backward slash?
This is how, it should be displayed.
Váci
Upvotes: 2
Views: 58
Reputation: 29501
Is there any way I can convert above name to display properly ignoring the first extra backward slash?
You can run the string through the JSON Parser, using JSON.parse()
.
Working Example:
const processString = (myString) => {
myString = JSON.parse('"' + myString + '"');
return myString;
}
console.log(processString('V\\u00E1ci'));
Why does this work?
Simply because when you convert a Javascript string into a JSON string, the JSON Parser will automatically convert any code point escape sequences into the corresponding Unicode characters.
Upvotes: 2
Reputation: 7621
It's not extra backwards slash in the string. the first \ is a escape character, so that you can add othervice not allowed characters in a string:
const s = "\"\"" // """"
What you need to do is to replace string '\u00E1' with the characer á. Like this
const name2 = name.replace("\\u00E1", "\u00E1"); // Váci
You can use the npm package https://www.npmjs.com/package/unescape-js to do this.
Upvotes: 1