Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript concat string with backspace

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 way that I can choose if I want to display the hardcoded string "abc" or not. For example,

f("\b\b"+"yz"); //should output "ayz"

I tried the same, but it does not work. In other words, I want to concat a string with a backspace character so that I can remove last characters from the string.

Can we do this in JavaScript?

EDIT The real code is too much big (its a HUGE 1 liner that concats many many strings). To map that in above example, we cannot edit the function f, so do whatever you want from outside function f.

like image 665
hrishikeshp19 Avatar asked Aug 09 '12 20:08

hrishikeshp19


People also ask

How do you backspace a string in JavaScript?

The "#" key is a backspace character, which means it deletes the previous character in the string.

What is JavaScript backslash?

The backslash ( \ ) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).

How do you initialize a string in JavaScript?

In JavaScript, we can initialize a String in the following two ways: Using String literal. Using "new" Keyword.


2 Answers

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"
like image 55
Kendall Frey Avatar answered Oct 26 '22 15:10

Kendall Frey


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.

like image 33
DGH Avatar answered Oct 26 '22 17:10

DGH