JavaScript concat string with backspace

Viewed 17141

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.

5 Answers

I'm processing the backspace \b, but it always has the ANSI erase in line \x1B[K after the \bs. So what I do is this:

function applyBackspaces(str) {
  // Catch character + \b or character + \b\x1B[K and delete it
  const re = /.?[\u0008](\u001b\[K)?/
  while (re.test(str)) {    
    str = str.replace(re, "");
  }
  return str;
}

// wrote "up", backspace+erase, backspace+erase (used backspace key)
// wrote "ls", backspace+backspace+erase (used clear line command C-u)
// wrote uptime
applyBackspaces('up\b\x1B[K\b\x1B[Kls\b\b\x1B[Kuptime') // uptime
Related