Remove all characters except alphanumeric and spaces with javascript

I like the solution povided by “Remove not alphanumeric characters from string. Having trouble with the [\] character” but how would I do this while leaving the spaces in place?

I need to tokenize string based on the spaces after it has been cleaned.

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>


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Check if object is an Observable

Similar Posts