feknuolis feknuolis - 1 year ago 87
jQuery Question

Need to test JS regex

When I type in my input the text appears on image. I want to make the code work like that:

When user types character that is recognized by regex then place it on image else just throw some error or do not let it type at all in the input field.

This is the regex:

[A-Z0-9a-z&,.-/()@*+!?"':; -]

I'm trying to achieve it like this:

$("#firstText").keyup(function () {
var value = $(this).val().toUpperCase();
var regex = "[A-Z0-9a-z&,.-/()@*+!?"':; -]";

} else {
alert('this is bad');

But I get this error:
Uncaught SyntaxError: Invalid or unexpected token

In this line:
var regex = "[A-Z0-9a-z&,.-/()@*+!?"':; -]";

Thanks in advance for any help.


The regex working fine now. Now I want to prevent typing characters in input when regex doesnt match the character. This is my code currently:

$("#firstText").keyup(function(e) {
var value = $(this).val().toUpperCase();
var regex = new RegExp(/[A-Z0-9a-z&,.-/()@*+!?"':; -]/);

if (regex.test(value)) {
} else {
return false;

Answer Source

The exact error you're seeing is because you are defining the variable as a double quoted string, with an unescaped double quote in it.

It shouldn't be a string anyway. It should be a regular expression like this.

var regex = /[A-Z0-9a-z&,.-/()@*+!?"':; -]/;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download