0

Sorry for another regex post but i have been trying to get a regex to work to check for unwanted characters in a string like @#?! I have tried

var cityreg=/^[^$%@!]+$/;

but it doesn't seem to work?

4
Contributors
6
Replies
8
Views
7 Years
Discussion Span
Last Post by shadiadiph
0

I personally don't like regex, as it takes alot of processing time and it's syntax is very difficult. You can better use a own written function that just simply loops the string, checking each character whether you want it in or not:

function checkString(var string) {

   var stringlength = string.length;
   var i;
   for (i = 0; i < stringlength; i++) {
      if ((string.substr(i, 1)) == "#") {
         alert("Invalid string!");
      }
   }
}

Anyway, for your regex question: see the following page: http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/

~G

0

Sorry for another regex post but i have been trying to get a regex to work to check for unwanted characters in a string like @#?! I have tried

var cityreg=/^[^$%@!]+$/;

but it doesn't seem to work?

You need to assign the regex pattern object to a variable and then use the test method of the regex object to check the input you pass to it.

function check()
{
    var text=prompt("Please enter some text","Harry Potter");
    var clean=/^[^$%@!]+$/; //Define your regex pattern
    if (text!=null && text!=""){
      if (clean.test(text)){ //Use your regex pattern to test input and return true or false
        alert(text + " is OK.")
      }else{
        alert(text + " contains an invalid character.")
      }
    }
}
1

You need to assign the regex pattern object to a variable and then use the test method of the regex object to check the input you pass to it.

Actually, no.

alert(/^[^$%@!]+$/.test(text))

works just as well.

Votes + Comments
Good catch. I guess literals are objects too, or at least they have methods.
0

fxm I don't hate regex that word is too short for how much I hate it but one thing I have to say is d5em is a regex genius works perfectly thanks

0

and you can add charaters to it like {} works great fantastic thanks a g'zillion

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.