Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a word with dot symbol using regexp javascript

Tags:

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

like image 809
Wondering Coder Avatar asked Aug 14 '26 02:08

Wondering Coder


1 Answers

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

like image 175
T.J. Crowder Avatar answered Aug 15 '26 15:08

T.J. Crowder



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!