Replace all non alphanumeric characters, new lines, and multiple white space with one space

Viewed 192492

I'm looking for a neat regex solution to replace

  • All non alphanumeric characters
  • All newlines
  • All multiple instances of white space

With a single space


For those playing at home (the following does work)

text.replace(/[^a-z0-9]/gmi, " ").replace(/\s+/g, " ");

My thinking is regex is probably powerful enough to achieve this in one statement. The components I think I'd need are

  • [^a-z0-9] - to remove non alphanumeric characters
  • \s+ - match any collections of spaces
  • \r?\n|\r - match all new line
  • /gmi - global, multi-line, case insensitive

However, I can't seem to style the regex in the right way (the following doesn't work)

text.replace(/[^a-z0-9]|\s+|\r?\n|\r/gmi, " ");

Input

234&^%,Me,2 2013 1080p x264 5 1 BluRay
S01(*&asd 05
S1E5
1x05
1x5

Desired Output

234 Me 2 2013 1080p x264 5 1 BluRay S01 asd 05 S1E5 1x05 1x5
10 Answers

To replace with dashes, do the following:

text.replace(/[\W_-]/g,' ');

When Unicode comes to play use

text.replace(/[^\p{L}\p{N}]+/gu," ");

EXPLANATION

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  [^\p{L}\p{N}]+           Any character except Unicode letters and digits
                           (1 or more times (matching the most amount possible))

JavaScript code snippet:

const text = `234&^%,Me,2 2013 1080p x264 5 1 BluRąy
S01(*&aśd 05
S1E5
1x05
1x5`
console.log(text.replace(/[^\p{L}\p{N}]+/gu, ` `))

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;
const processStirng = (str) => (
    str
    .replace(/[^a-z0-9\s]/gi, '') // remove all but alpha-numeric and spaces
    .replace(/ +/g, ' '); // remove duplicated spaces
);
processSting(' $ your    string    here #');
Related