Wondering Coder
Wondering Coder

Reputation: 1702

Matching a word with dot symbol using regexp javascript

I have a search feature. I want to check if the user enter a text word/sentence with dot (.) on it.

Example:
-anyword.anyword.
-.
-.anyword

Once I detect that he/she entered a value that has a dot on it I will consider that as invalid.

I know I can do this using regexp but I'm still in the process of learning it. So anyone could shed me a light here would be appreciated :).

Upvotes: 3

Views: 9871

Answers (4)

PHP Guru
PHP Guru

Reputation: 1568

If you want to put the check right in your search form, you can use a regular expression that matches a string of non-dot characters:

<input type="text" name="search" pattern="[^\.]*" title="Please enter a string of non-dot characters">

Entering a dot into the search field will cause an error. This is HTML5 so old browsers will just ignore it.

The pattern attribute, when specified, is a regular expression which the input's value must match for the value to pass constraint validation. It must be a valid JavaScript regular expression

Upvotes: 0

Devang Rathod
Devang Rathod

Reputation: 6736

try this

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

var str = "test.test";
if(str.indexOf('.') === -1){
  alert("no dot found.");
}
else{
    alert("dot found.");
}

Upvotes: 1

Raman
Raman

Reputation: 1376

Better to use indexOf function of String then Regexp for this as Regexp will be an overkill in this scnerio:

Use MyString.indexOf('.') if it return -1 there is no dot in the string. If returned value is some integer like 0,1,2 etc that gives the position of Dot in the string. So -1 tell that there is no Dot

Example:

if(MyString.indexOf('.') === -1)
{
   //No Dot is there, continue search
}
else
{
   //Invalid string, dot is present
}

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075925

You can use String#indexOf:

if (theString.indexOf(".") !== -1) {
    // It has a dot
}

But if you really want to use regular expressions (which would be overkill for just finding a .):

if (/\./.test(theString)) {
    // It has a dot
}

The /\./ part is the regular expression. The beginning and ending / are the regex delimiters, like " and ' are for strings. The content of the regex is \. We need the backslash before the . because otherwise, within a regex, . means "match any character". The backslash before it "escapes" it and tells the regex to literally match a dot. (We don't need that in the String#indexof example because indexOf doesn't have any special handling of ..)

Upvotes: 7

Related Questions