Skip to content Skip to sidebar Skip to footer

How Do I Programmatically Create A Double Escape?

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

Solution 1:

No, you can't. It's not that the backslash is ignored in the split.

Instead, the problem is that the backslash isn't in the string:

"Hello\ World"; // "Hello World"

Therefore, once the string literal has been parsed, you can't recover the slash.

However, ECMAScript 6 introduces template strings. And with String.raw, you can recover the raw string form:

`Hello\ World`;           //  "Hello World"String.raw`Hello\ World`; //  "Hello\ World"

Solution 2:

I tried this method: I ran your code and variations. To get around the problem of escaping backlashes, I though to make the function myself by testing for the CharCode. The function output was index=5 as expected.

functionf(x) {
    var a = -1,i,n=x.length;
    for(i=0;i<n;i++)
    {
        if(x.charAt(i)==String.fromCharCode(92))
        {
            a=i;
            break;
        }
    }
    return a.toString();
}

functionh(x) {
    document.getElementById('in').innerHTML = x;
    document.getElementById('out').innerHTML = f(x);
}

<button type="button"
onclick="h('Hello\\ World')">
Run</button>

<pid="in"></p>
<hr>
<pid="out"></p>

Post a Comment for "How Do I Programmatically Create A Double Escape?"