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()
eg:
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
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"))