four-eyes
four-eyes

Reputation: 12384

Regex expression retuns unexpected result on special characters

I want to check whether a string contains special characters. I am using the following regex for this

Trying it online with regex101 it works perfectly. However, when I include this in my code, it does not work. It always returns false... Why is that?

The input field handling the user input.

<input
    placeholder={placeholder}
    type='text'
    autoComplete='off'
    value={this.state.text}
    onChange={event => this.handleOnChange(event)}
/>

The handleOnChange handling whenever something is typed.

handleOnChange = event => {
    const text = event.target.value;
    this.setState({
        text
    });

    this.checkForSpecialCharacter(text)
}


checkForSpecialCharacter = text => {
    const specialCharacters = new RegExp('/[ !@#$%^&*()_+=`~:;",.\-\[\]\{\}\'\\\|\<\>\/\?]/');
    console.log(specialCharacters.test(text)) // <- logs false
    this.setState({
        foo: {
            ...this.state.foo,
            specialCharacter: specialCharacters.test(text),
        }
    });
}

Upvotes: 0

Views: 43

Answers (1)

Sweeper
Sweeper

Reputation: 270890

If you are using '' to create the regex, you should not add the / at the start and end and you should escape the backslashes:

new RegExp('[ !@#$%^&*()_+=`~:;",.\\-\\[\\]\\{\\}\\'\\\\\\|\\<\\>\\/\\?]');

That's a lot of backslashes, so you should just write it with // as the delimiters:

const specialCharacters = /[ !@#$%^&*()_+=`~:;",.\-\[\]\{\}\'\\\|\<\>\/\?]/;

Upvotes: 2

Related Questions