Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

javascript - What's the use of the [] backspace regex?

[] matches a backspace character apparently. I can't understand how a string could contain a backspace character. Can someone give me a concrete example of how this would be used? Thanks so much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While all the others are right in general (that is a word boundary), does mean backspace inside character classes:

[]

This will indeed match a backspace character. It's just an ASCII control character that can appear in text (ASCII code 8, or 10 in octal). I suppose it's mostly used for legacy reasons, to add diacritical marks (e.g. you could do a, backspace, , to get á). Today these have been mostly replaced by Unicode combining marks.

How a string containing a backspace will ultimately look depends on the software that renders it. Consoles will probably still move the cursor back and overwrite what was there if the backspace is followed by new other characters. To see this, fire up an interactive scripting console (like node.js if you want to try it in JavaScript), and run

> console.log("abcdef")
adef

Note that, had you omitted def, you'd just get abc, because the backspace itself does not erase anything. It only moves the cursor back.

On the other hand, your browser might just ignore it in an input field. For instance, check out a Unicode converter, enter the JavaScript input abcdef in the bottom left input, hit "convert", and the "Characters" output will not have the bc erased.

By the way being a backspace in character classes is not unique to JavaScript, but interpreted this way in most regex flavors.

Further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...