I have code like this:
string.replace(/(.|\r\n)\x08/g, '');
that replaces backspace and one character before it, but it will not work for cases where there are more then one backspace in a row, like 'foo\b\b'
. How can I remove characters that are before backspaces so I get string 'f'
.
I have code like this:
string.replace(/(.|\r\n)\x08/g, '');
that replaces backspace and one character before it, but it will not work for cases where there are more then one backspace in a row, like 'foo\b\b'
. How can I remove characters that are before backspaces so I get string 'f'
.
-
If you replace one character before the backspace, then how do you e up with
f
out offoo\b\b
? This means you want to replace as many characters as backspaces, doesn't it? – cezar Commented Jun 23, 2016 at 13:08 - @cezar Yes, you're right. – jcubic Commented Jun 23, 2016 at 14:35
-
What should be the expected result for
foo\bo\b\b
? – Lucas Araujo Commented Jun 23, 2016 at 15:04 - Ok, I believe my answer should meet your requirements then. Let me know if it doesn't. – Lucas Araujo Commented Jun 23, 2016 at 15:16
4 Answers
Reset to default 6You can try this:
str="abc\b\bdefg";
while(str.match(/\w\x08/)){
str=str.replace(/\w\x08/g,"");
}
It will keep removing a "character + back space" sequence, while they are still in the string.
'+' means '1 or more', so try string.replace(/(.|\r\n)+\x08/g, '')
If you just want to delete one or two 0x08 characters in the string and the character before them just change the regex to
/(.|\r\n)\x08{1,2}/g
But I think what you want to do is delete 1 character per 0x08 you can do this like this
/((.|\r\n)\x08|(.|\r\n){2}\x08{2})/g
for two. If you want to do it for more I think it will just be faster to write a function that goes over the string char by char and parses it one iteration
function removeBackslashes(str){
var result = "";
for(var i in str){
if(str.charCodeAt(i) == 8)
{
result = result.slice(0, -1);
}else{
result += str.charAt(i);
}
}
return result;
}
var b = removeBackslashes('foo\b\basd');
console.log(b, b.length);
I came up with this:
'foo\b\b'.replace(/((?:[^\x08]|\r\n)+)(\x08+)/g, function(_, chars, backspaces) {
return chars.replace(new RegExp('(.|\r\n){' + backspaces.length + '}$'), '');
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745386863a4625478.html
评论列表(0条)