JavaScript concat string with backspace

I have a f function similar to

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

Now I want to use the special JavaScript script "\ b" JavaScript in such a way that I can choose whether 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 concatenate a string with a backspace character so that I can remove the last characters from the string.

Can we do this in JavaScript?

EDIT The actual code is too large (its huge liner, which combines many lines). To display this in the above example, we cannot edit the function f, so do whatever you want from the external function f.

+7
source share
4 answers

The problem arises because \b is another character in ASCII code. Special behavior is observed only when it is implemented by some line reader, for example, a text terminal.

You will need to implement the backspace behavior 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 as follows:

 var str = RemoveBackspaces(f("\b\byz")); // returns "ayz" 
+6
source

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

You should probably just use string.substring or string.substr , both of which return part of the string. You can get the substring from 0 to the length of the string minus 2, and then combine it with "yz" or something else.

+1
source

Interest Ask. First, I checked some assumptions about \ b in JS.

If you try this:

console.log ('a \ b \ Byz');

You will get the same answer "abcyz".

This means that this is not a function of concatenation, but a fundamental error in the approach.

I would change your approach to using SubString, then take the \ b index and strip out the previous character.

+1
source

Something like that:

 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 can use recursion!

Note that this is a bit 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); } 
+1
source

All Articles