I want to replace all whitespaces except the first and the last one as this image.
How to replace only the red ones?
how to replace the red space
I tried :
.replace(/\s/g, "_");
but it captures all spaces.
I suggest match and capture the initial/trailing whitespaces that will be kept and then matching any other whitespace that will be replaced with _:
var s = " One Two There ";
console.log(
s.replace(/(^\s+|\s+$)|\s/g, function($0,$1) {
return $1 ? $1 : '_';
})
);
Here,
(^\s+|\s+$) - Group 1: either one or more whitespaces at the start or end of the string| - or\s - any other whitespace.The $0 in the callback method represents the whole match, and $1 is the argument holding the contents of Group 1. Once $1 matches, we return its contents, else, replace with _.
You can use ^ to check for first character and $ for last, in other words, search for space that is either preceded by something other than start of line, or followed by something thing other than end of line:
var rgx = /(?!^)(\s)(?!$)/g;
// (?!^) => not start of line
// (?!$) => not end of line
console.log(' One Two Three '.replace(rgx, "_"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With