Regular expression for all printable characters in JavaScript

前端 未结 4 1738
时光说笑
时光说笑 2020-11-27 20:33

Looking for a regular expression for that validates all printable characters. The regex needs to be used in JavaScript only. I have gone through this post but it mostly talk

4条回答
  •  误落风尘
    2020-11-27 21:02

    To validate a string only consists of printable ASCII characters, use a simple regex like

    /^[ -~]+$/
    

    It matches

    • ^ - the start of string anchor
    • [ -~]+ - one or more (due to + quantifier) characters that are within a range from space till a tilde in the ASCII table:


    - $ - end of string anchor

    For Unicode printable chars, use \PC Unicode category (matching any char but a control char) from XRegExp, as has already been mentioned:

    ^\PC+$
    

    See regex demos:

    // ASCII only
    var ascii_print_rx = /^[ -~]+$/;
    console.log(ascii_print_rx.test("It's all right.")); // true
    console.log(ascii_print_rx.test('\f ')); // false, \f is an ASCII form feed char
    console.log(ascii_print_rx.test("demásiado tarde")); // false, no Unicode printable char support
    // Unicode support
    console.log(XRegExp.test('demásiado tarde', XRegExp("^\\PC+$"))); // true
    console.log(XRegExp.test('‌ ', XRegExp("^\\PC+$"))); // false, \u200C is a Unicode zero-width joiner
    console.log(XRegExp.test('\f ', XRegExp("^\\PC+$"))); // false, \f is an ASCII form feed char

提交回复
热议问题