Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Chinese characters with regular expression in javascript

I need a regular expression to test a string. The string can only contain English letters, number, hyphen and underscore.

previously I have one to test a string whether it only contains positive numbers(zero included); I used:

if(!/^\d+$/.test(number)) {
    alert('..bla');
} else {
    return true;
};

So I want a similar one. I have read:

Regular expressions and Chinese;

and Regex Letters, Numbers, Dashes, and Underscores;

But these two does not seem to fix my problem.

    !/[a-zA-Z0-9\-\_]+$/.test('_-bla')  // return false
    !/[a-zA-Z0-9\-\_]+$/.test('_-bl我a')  // return false
    !/[a-zA-Z0-9\-\_]+$/.test('_-bl我')  // return true
    !/[a-zA-Z0-9\-\_]+/.test('_-bl我')  // return false
    !/[a-zA-Z0-9\-\_]+/.test('_-bl我a') // return false

Thanks in advance. :)

like image 997
shrekuu Avatar asked Mar 11 '26 22:03

shrekuu


2 Answers

Use ^[-\w]+$. \w matches digits, alphabets, _.

/^[-\w]+$/.test('_-bla')   // true
/^[-\w]+$/.test('_-bl我a') // false
/^[-\w]+$/.test('_-bl我')  // false
/^[-\w]+$/.test('_-bl我')  // false
/^[-\w]+$/.test('_-bl我a') // false
like image 149
falsetru Avatar answered Mar 14 '26 12:03

falsetru


I assume you're looking for this output. Add the caret (^) which means start of string and ($) meaning end of string to your regular expressions.

/^[a-zA-Z0-9_-]+$/.test('_-bla');    // True
/^[a-zA-Z0-9_-]+$/.test('_-bl我a');  // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我');   // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我');   // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我a');  // False

You can just use \w instead which matches word characters (a-z, A-Z, 0-9, _)

/^[\w-]+$/
like image 38
hwnd Avatar answered Mar 14 '26 12:03

hwnd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!