Entwickler Entwickler - 1 month ago 14
Javascript Question

Regex to test string contain a specific pattern and exclude specific symbol using javascript

I would like to test a specific pattern using JavaScript.

Following is scenario.

I don't want to allow comma (,) in a string. For example 12,34 should return false and rest anything gives true.

I have read some tutorial to exclude some character using ^. As simple example I am doing something like this

/[^,][1-9]/g.test('12,34')


but it give true. Although I exclude the comma.

Valid result should be 12.34 or 1234 etc. but not 12,34.

I want to extend this to later (12.34) or (ABC) etc. as valid where string start with '(' and ends with ')' and can contain anything inside except comma.

Answer

You can change your regex and use anchors like this:

^[^,]+$

This pattern will match string where the line starts and ends with whatever string not having a comma

On the other hand, if you want to allow 12.34, 1234 or ABC patterns, then you could use:

^[\dA-Z]+(?:\.[\dA-Z]+)?$

Working demo

Comments