简体   繁体   中英

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 :).

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 . .)

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
}

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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM