Mike Tabag Estonanto
Mike Tabag Estonanto

Reputation: 348

Javascipt Replace all characters with underscore except the first word

I want to replace all the characters in a string with underscore except for the first word, but my code replaces all the characters with an underscore.

Expected result: Hello ___ __ _________

var regex = /[a-z0-9,.':!?"]/gi;
var str = "Hello I'm an astronaut";
console.log(str.replace(regex, "_"));

Upvotes: 2

Views: 324

Answers (4)

The fourth bird
The fourth bird

Reputation: 163362

Another approach is using a lookbehind for the browsers that support it:

(?<=^\S+\s.*)\S
  • (?<= Positive lookbehind, assert what is at the left is
    • ^\S+\s.* Match 1+ non whitespace chars followed by a whitspace char at the start of the string
  • ) Close lookbehind
  • \S Match a single non whitespace char

Regex demo

var regex = /(?<=^\S+\s.*)\S/g;
var str = "Hello I'm an astronaut";
console.log(str.replace(regex, "_"));

Or using a capture group for the part that you want to keep, and replace the matches with an underscore:

^(\S+)|\S
  • ^(\S+) Start of the string, capture 1+ non whitespace chars in group 1 (Denoted by g1 in the example code
  • | Or
  • \S Match a single non whitespace char

Regex demo

var regex = /^(\S+)|\S/g;
var str = "Hello I'm an astronaut";
console.log(str.replace(regex, (m, g1) => g1 ? g1 : "_"));

Upvotes: 0

Hao Wu
Hao Wu

Reputation: 20699

It is possible to achieve it by just using regex though

var regex = /(^\S*\s*)?\S/gm;
var str = "Hello I'm an astronaut";
console.log(str.replace(regex, "$1_"));

Upvotes: 0

StarshipladDev
StarshipladDev

Reputation: 1145

var regex = /[a-z0-9,.':!?"]/gi;
var str = "Hello I'm an astronaut";
console.log(str.substr(0,str.indexOf(' ')) +str.substr(str.indexOf(' ')).replace(regex, "_"));

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

I would use a split and regex approach here:

var str = "Hello I'm an astronaut";
var first = str.substr(0, str.indexOf(' '));                      // finds first word
var rest = str.substr(str.indexOf(' ') + 1).replace(/\S/g, "_");  // find other words
console.log(first + " " + rest);

Upvotes: 2

Related Questions