JavaScript concat string with backspace

后端 未结 4 653
清酒与你
清酒与你 2020-12-17 20:18

I have a function f similar to

function f(str){
    alert(\"abc\"+str);
}

Now, I want to use JavaScript special charecter \"\\b\" in such a

相关标签:
4条回答
  • 2020-12-17 20:21

    Interesting question. I first checked some assumptions about \b in JS.

    If you try this:

    console.log('abc\b\byz');

    You get the same answer of 'abcyz'.

    This means, it is not a function of concatentation, but a fundamental error in the approach.

    I would modify your approach to use SubString, then to take the index of \b and slice out the previous character.

    0 讨论(0)
  • 2020-12-17 20:24

    EDIT: I realized this may not be what the OP was looking for, but it is definitely the easier way to remove characters from the end of a string in most cases.

    You should probably just use string.substring or string.substr, both of which return some portion of string. You can get the substring from 0 to the string's length minus 2, then concatenate that with "yz" or whatever.

    0 讨论(0)
  • 2020-12-17 20:35

    Something like this:

    function f(str, abc){
       if(!abc) abc = "abc";
       if (str.indexOf("\b") != "undefined")
       {
           abc = abc.slice(0,-1);
           str = str.replace("\b","");
           f(str, abc);
       }
       else alert(abc+str);
    }
    

    and as an added bonus you get to use recursion!

    note that this is a little slower than doing it this way:

    function f(str){
        var count = 0;
        var abc = "abc";
        for(var i = 0; i < str.length; i++)
        { 
           if(str[i] = "\b") //at least i think its treated as one character...
           count++;
        }
        abc = abc.slice(0, count * -1);
        alert(abc+str);
    }
    
    0 讨论(0)
  • 2020-12-17 20:45

    The problem comes from the fact that \b is just another character in the ASCII code. The special behaviour is only when implemented by some string reader, for example, a text terminal.

    You will need to implement the backspace behaviour yourself.

    function RemoveBackspaces(str)
    {
        while (str.indexOf("\b") != -1)
        {
            str = str.replace(/.?\x08/, ""); // 0x08 is the ASCII code for \b
        }
        return str;
    }
    

    Example: http://jsfiddle.net/kendfrey/sELDv/

    Use it like this:

    var str = RemoveBackspaces(f("\b\byz")); // returns "ayz"
    
    0 讨论(0)
提交回复
热议问题