Remove all characters except alphanumeric and spaces with javascript
input.replace(/[^\w\s]/gi, '')
Shamelessly stolen from the other answer. ^
in the character class means "not." So this is "not" \w
(equivalent to \W
) and not \s
, which is space characters (spaces, tabs, etc.) You can just use the literal if you need.
I know this is an old thread, but so popular that appears at the top of a Google search. So, as an alternative, the accepted answer and comment from 3limin4t0r inspired me to:
.replace(/\W+/g, " ")
IMHO
const input = document.querySelector("input");
const button = document.querySelector("button");
const output = document.querySelector("output");
button.addEventListener("click", () => {
output.textContent = input.value.replace(/\W+/g, " ");
})
<input>
<button>Replace</button>
<p>
<output></output>
</p>