I have a string with an escape character:
var a = "Hello World";
I want to split the string into an array of characters which includes the escape character:
var a = "Hello World";
/* Do something here */
a; // I want output: ["H","e","l","l","o",""," ","W","o","r","l","d"]
Typically I split the string using:
a=a.split('');
But of course this does not work because the escape character is ignored during the split.
var a = "Hello World";
a=a.split('');
a; // outputs ["H","e","l","l","o"," ","W","o","r","l","d"]
Now I know in order to get the results I want I have to use a double escape. I know that my string should look like:
var a = "Hello\ World";
But that is not the string I have, I am not typing in the string manually it is generated. So I fully understand that I need a double escape but I can not manually create one. I need to know how to programmatically transform "Hello World"
into "Hello\ World"
.
Is there some magical function that will escape all backslashes? Is there a doubleEscape()
function I am not aware of, or maybe there is some regex replace function that can help me out.
I do not want the answer "use a double escape" or "your string needs to be 'Hello World'. I am fully aware that this is what I need to do but I need to programmatically escape the escape character, it can not be done manually.
I have attempted something like this:
var a = "Hello World";
a = a.replace("", "");
But of course this doesn't work because the escape character is ignored during the replace. I have tried things like:
var a = "Hello World";
a = a.replace("", "");
But this gives an error. I believe it is interpreting the search parameter as a regex, which is an invalid regex, which causes an error.
Another post that was similar suggested this:
var a = "Hello World";
a = a.replace(/\/g, '\\');
a; // outputs "Hello World";
This does not work. The string remains as if the replace was not executed.
Any suggestions?
See Question&Answers more detail:
os