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

Give space to array of signs in the string

considering each sign always in the start or end of the string only, we want to give each sgin a space before or after so as a word:

The desired result is commented, My function has an issue as you see:

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {
    const sgins = ['?', '!', '...', '?!', '!?', '!!', '.'];
  for (let a = 0; a < sgins.length; a++) {
    const split = string.split(sgins[a]);
    string = string.replaceAll(sgins[a], ` ${sgins[a]} `).trim();
  }
  console.log(string);
}

How would you do this?

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 :

You could use a simple regex:

string.replace(/$[?!.]+/, '$& ');

Means replace all continuous ?!. characters with the characters plus a space in the beginning of the string. The same for the end.

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {
   string = string.replace(/^[?!.]+/, '$& ').replace(/[?!.]+$/, ' $&');
   console.log(string);
}

If you need exact prefixes you can build the regexp:

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {

  const sgins = ['?', '!', '...', '?!', '!?', '!!', '.'];

  const options = sgins.sort((a, b) => b.length - a.length).map(prefix => [...prefix].map(c => '\\' + c).join('')).join('|');

  string = string.replace(new RegExp('^(' + options + ')'), '$1 ').replace(new RegExp('(' + options + ')$'), ' $1');
  
  console.log(string);
}
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