Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript & regex : How do I check if the string is ASCII only?

I know I can validate against string with words ( 0-9 A-Z a-z and underscore ) by applying W in regex like this:

function isValid(str) { return /^\w+$/.test(str); } 

But how do I check whether the string contains ASCII characters only? ( I think I'm close, but what did I miss? )

Reference: https://stackoverflow.com/a/8253200/188331

UPDATE : Standard character set is enough for my case.

like image 369
Raptor Avatar asked Jan 14 '13 03:01

Raptor


People also ask

What is the JavaScript used for?

Javascript is used by programmers across the world to create dynamic and interactive web content like applications and browsers. JavaScript is so popular that it's the most used programming language in the world, used as a client-side programming language by 97.0% of all websites.

Is JavaScript a coding?

JavaScript is a lightweight interpreted programming language. The web browser receives the JavaScript code in its original text form and runs the script from that.

Is JavaScript easy to learn?

JavaScript is a simple and easy-to-learn programming language as compared to other languages such as C++, Ruby, and Python. It is a high-level, interpreted language that can easily be embedded with languages like HTML.

Is JavaScript a free download?

For those want to learn to program, one of the biggest advantages of JavaScript is that it is all free.


1 Answers

All you need to do it test that the characters are in the right character range.

function isASCII(str) {     return /^[\x00-\x7F]*$/.test(str); } 

Or if you want to possibly use the extended ASCII character set:

function isASCII(str, extended) {     return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str); } 
like image 62
zzzzBov Avatar answered Sep 20 '22 17:09

zzzzBov