Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all spaces except the first & last ones

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.

like image 720
Mustapha Bouh Avatar asked Dec 03 '25 07:12

Mustapha Bouh


2 Answers

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 _.

like image 190
Wiktor Stribiżew Avatar answered Dec 04 '25 19:12

Wiktor Stribiżew


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, "_"));
like image 21
MrGeek Avatar answered Dec 04 '25 21:12

MrGeek