Redbox
Redbox

Reputation: 1477

jquery : regex to detect + and - only

i have a code to allow input only numbers and letter:

        if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
            this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
        }

how do i change the filter to allow the symbol : + and - and remove numbers, letters and others? It must be has something to do with regex, which i not sure on how to do it. Any quick solution? thanks.

Upvotes: 0

Views: 67

Answers (1)

David M
David M

Reputation: 72920

You can add those characters to the character set, and remove the ones you now want to clear out. However, in here, the - symbol has a special meaning and must be escaped like this:

    if (this.value.match(/[^+\-]/g)) {
        this.value = this.value.replace(/[^+\-]/g, '');
    }

As inhan points out in his comment, since the hyphen is the last character in the group, and therefore unambiguous, it may well be possibly to omit the escaping to have just this regex:

/[^+-]/g

But neither of us is totally sure if this will always work, whereas the escaped form certainly will.

Upvotes: 2

Related Questions