Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substitute all letters except the first in each word

text = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,";

substitute_with = "_";

const regex = '\B[A-Za-z]';
// const regex = '\B\w';
// const regex = '(\w{1})\w*';

var result = text.replaceAll(regex, substitute_with);

I would like to substitute with underscore all letters except the first in each word.

I have failed miserably. Could you help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the g (global) flag with replace():

const text = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,";
const substitute_with = "_";

const regex = /\B[A-Za-z]/g;
var result = text.replace(regex, substitute_with);

console.log(result);

L____ I____ h__ b___ t__ i_______’s s_______ d____ t___ e___ s____ t__ 1500_,


Of course, this can also be done without regex using split(), substring(), repeat() and join():

const result = text.split(' ')
    .map(w => w.substring(0, 1) + substitute_with.repeat(w.length - 1))
    .join(' ');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading