问题描述
我的函数f类似于
function f(str){
alert("abc"+str);
}
现在,我想在这样的情况下使用JavaScript特殊字符\ b如果我想显示硬编码字符串abc,我可以选择一种方式。例如,
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.
我们可以用JavaScript吗?
Can we do this in JavaScript?
编辑
真正的代码太大了(它是一个巨大的1个班轮,可以连接许多字符串)。要在上面的示例中映射,我们不能编辑函数f,所以从外部函数f做任何你想做的事情。
EDITThe 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.
推荐答案
问题来自于 \b
只是ASCII码中的另一个字符。特殊行为仅在某些字符串阅读器实现时才会显示,例如文本终端。
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;
}
示例:
像这样使用:
var str = RemoveBackspaces(f("\b\byz")); // returns "ayz"
这篇关于带有退格的JavaScript concat字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!