How to exclude last space from regex?

I have input box in my react component

const {Component} = React;

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: "",
        };
    }

    restrictSpecialCharacters = (e) => {
        const nospecial = /^[A-Za-z0-9]+$/;
        const textValue = e.target.value;
        if (textValue.match(nospecial)) {
            this.setState({ searchText: textValue })
        }
    };

    render() {
        return <input
            type="text"
            className="form-control form-control-lg material-textfield-input"
            name="carrierACNumber"
            value={this.state.searchText}
            onChange={(e) => this.restrictSpecialCharacters(e) }
            required
        />;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

it works as expected but when I try to remove last character on pressing backspace then it does not remove it. How can I make regex that removes that last character?

Answer

The reason it’s not allowing you to remove the last character is because the + in your regex means “one or more” which does not allow for 0 characters to appear; it no longer matches the regex.

If you change your regex to /^[A-Za-z0-9]*$/ that should resolve your problem, as * is 0 or more:

const {Component} = React;

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: "",
        };
    }

    restrictSpecialCharacters = (e) => {
        const nospecial = /^[A-Za-z0-9]*$/;
        const textValue = e.target.value;
        if (textValue.match(nospecial)) {
            this.setState({ searchText: textValue })
        }
    };

    render() {
        return <input
            type="text"
            className="form-control form-control-lg material-textfield-input"
            name="carrierACNumber"
            value={this.state.searchText}
            onChange={(e) => this.restrictSpecialCharacters(e) }
            required
        />;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>