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?
>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);
}