regex - How to replace one backspace or two backspaces in a row and character before them in javascript? - Stack Overflow

I have code like this:string.replace((.|rn)x08g, '');that replaces backspace and one cha

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'.

Share Improve this question edited Jun 23, 2016 at 13:09 cezar 12k6 gold badges50 silver badges90 bronze badges asked Jun 23, 2016 at 12:57 jcubicjcubic 66.8k58 gold badges249 silver badges455 bronze badges 4
  • If you replace one character before the backspace, then how do you e up with f out of foo\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
Add a ment  | 

4 Answers 4

Reset to default 6

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信