1

How do I make a ASCII 7 bell character in JavaScript's regular expressions?

My regex: ^[#&][^ \a]{0,200}$

The regex above causes literally to not take the character a instead of the ASCII 7 character.

See example: https://regex101.com/r/5nMNL4/1

Even at the explanation on the right side of Regex101 it says:

\a matches the bell character (ASCII 7)

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

2 Answers2

3

You cannot write "\a" and expect a bell char in the string as JS escape sequences do not include this one.

However, to find it in the text, use /\x07/:

enter image description here

console.log(/\x07/.test("\x07"));

Another possible issue is that you are trying to match a Unicode char, then see Target a bell character with a regular expression.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    As a side note, **do not believe everything regex101.com tells you**, check the documentation and test your regexps in the target environment - always. Regex101 still has bugs. – Wiktor Stribiżew Nov 16 '16 at 21:03
  • I have a related question about non-printable control characters here: https://stackoverflow.com/questions/73633022/what-is-the-purpose-of-non-printable-control-characters-in-this-email-validation. I think user6410654 question and your answer here are helpful in getting to the bottom of it. Thank you! I observe that if I `console.log('\x07');` in node.js running in the macOS terminal, the computer makes a beeping sound. – jamesmortensen Sep 27 '22 at 09:12
0

According to MDN, the \a modifier is not on the list of supported modifiers for regular expressions in Javascript.

If you want to match the symbol you can use \u2407

console.log( "Test␇String".match(/\u2407/) )

If you want to match the bell character  you'd use \u0007

var s = document.getElementById('test').innerHTML;
console.log( s.match(/\u0007/) )
<div id="test">&#7;test</div>
adeneo
  • 312,895
  • 29
  • 395
  • 388