Replace all characters with "_" except the 1st character of each word

2

I want to replace a sentence with all characters with _ except the 1st character of each word in JavaScript.

  

Q

asked by anonymous 20.09.2016 / 01:07

2 answers

3

Alternatively, you can use String.replace . in conjunction with regular expression /\B\w/g :

var valor = 'stack overflow em portugues';

var substituto = valor.replace(/\B\w/g, '_');
// s____ o_______ e_ p________

Where \B is the opposite of \b , \b it is limited to correspond to an exact pattern or word, depending on the position in which it is inserted, for example, the expression \b\w corresponds to f and b in foo bar , otherwise \w\b corresponds to o and r .

The expression \B\w corresponds to oo and ar and \w\B to fo and ba . In this other question you have more details about: What is a boundary ( \b ) in a regular expression ?

The modifier g indicates that it should be made a global search, does not return the first time the pattern is matched.

To display the remaining letters in upper case, use the string.toUpperCase :

var valor = 'stack overflow em portugues';
var substituto = valor.replace(/\B\w/g, '_').toUpperCase();

console.log(substituto);
// S____ O_______ E_ P________
    
21.09.2016 / 15:43
1

The following logic will solve your problem:

var text = "QUOTE";

 function replaceString(text){
    var textRefact;
    for(var i = 0; i < text.length; i++){
       if(i == 0){
       textRefact = text.charAt(i);
    }else{
       textRefact += "_";
    }
 }
   return textRefact;
 }

var newText = replaceString(text);

console.log(newText);
    
21.09.2016 / 13:41