I have an array of strings. I need to add slashes to the array of values dynamically. How can I do this in JavaScript?
Input:
["opera","admatic"]
Expected Output:
["\"opera\"","\"admatic\""]
I have an array of strings. I need to add slashes to the array of values dynamically. How can I do this in JavaScript?
Input:
["opera","admatic"]
Expected Output:
["\"opera\"","\"admatic\""]
You've said you need to add "backslashes", but you don't. You just need to add quotes. In a string literal delimited with double quotes ("example"
), you use a backslash in front of a double quote in order to have the quote in the string (instead of having it end the string literal), like this: "here's a quote: \" that was it."
. But there is no backslash in the string, just in the string literal in the code to write it. Alternatively, you can use a string quoted with single quotes, in which you have to escape single quotes, not double quotes: 'here\'s a quote: " that was it.'
So we want to add quotes at the beginning and end of those array entries.
To modify all of the entries in an array, typically you use the map
method to create a new array with the modified values in it, like this:
const original = ["opera","admatic"];
const updated = original.map(str => '"' + str + '"');
console.log("original:", original);
console.log("updated:", updated);
You could also use a template literal (delimited with backticks) to build the new string instead of string concatenation:
const updated = original.map(str => `"${str}"`);
const original = ["opera","admatic"];
const updated = original.map(str => `"${str}"`);
console.log("original:", original);
console.log("updated:", updated);
you need double back slashes
const oldArray = ["opera","admatic"];
const newArray = oldArray.map(item => '\\"'+item+'\\"');