5

Trying to get rid of any space that is around a non-alphanumeric character without removing the said character like /\s*(\W)\s*/g would by default.

Is there a way to target only the spaces with .replace()?

e.g.:

var regex = "/\s*(\W)\s*/g";
var text = "Words  : \"  text docs\"";
var text = text.replace(regex , "");
console.log(text)

expected text :"Words:"text docs"

Something like remove white spaces between special characters and words python but in javascript

karel
  • 5,489
  • 46
  • 45
  • 50
Rnikolai
  • 57
  • 5

1 Answers1

2

You should bear in mind that \W matches any "non-word" character that is not an ASCII letter, digit, or _. \W, in JS regex, is equal to [^A-Za-z0-9_]. Thus, it also matches whitespace that you need to remove. To be able to only match non-whitespace non-word chars, you need to replace \W with a [^\w\s] pattern.

So, the rest is just replacing the match with the replacement backreference to the Group 1 value, which is $1 in JS:

text = text.replace(/\s*([^\w\s])\s*/g , "$1")

See the regex demo

JS demo:

console.log("Some - text +=@!#$#$^%* here .        ".replace(/\s*([^\w\s])\s*/g , "$1"))
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Enrico Maria De Angelis and Ritesh Khandekar suggested both of the fixes in comments , thank you for the link to explanation of replacement backreference – Rnikolai Mar 06 '20 at 21:01