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?
2
Answers
You could use a simple regex:
Means replace all continuous
?!.
characters with the characters plus a space in the beginning of the string. The same for the end.If you need exact prefixes you can build the regexp:
First off I would not use split() to be honest with You. I would write this like that, but this is not optimal code. This is not for all cases, I had to replace some signs of Your array to work. If You want to make it perfect, then you have to program this for a lot of different cases so code would be a little bigger. Cause for example what if there already is space? ETC.