Reputation: 23
let text = "'I'm the cook,' he said, 'it's my job.'";
// Change this call.
function replaceQuotes(string) {
const actionReplace = string.replace(/(^')|('$)|('(?=.*)(?=\s))|(?: '(?=.*))/g, "#");
return actionReplace
}
console.log(replaceQuotes(text));
//expected result → "I'm the cook," he said, "it's my job."
//actual result → "zI'm the cook,z he said,zit's my job.z"
Upvotes: 1
Views: 104
Reputation: 91385
In the last alternation you have a space that is not replaced.
Just add this space in the replacement part, for doing this, I've remove all your useless groups (that slow down the process) and create another one that contains the space to keep.
let text = "'I'm the cook,' he said, 'it's my job.'";
// Change this call.
function replaceQuotes(string) {
const actionReplace = string.replace(/^'|'$|'(?=\s)|( )'(?=.*)/g, '$1"');
return actionReplace
}
console.log(replaceQuotes(text));
//expected result → "I'm the cook," he said, "it's my job."
//actual result → "zI'm the cook,z he said,zit's my job.z"
Upvotes: 1
Reputation: 17590
for "
charactes \
is put in front of it.
So you can just change "#"
to "\""
or u can change "#"
to '"'
let text = "'I'm the cook,' he said, 'it's my job.'";
function replaceQuotes (string){
const actionReplace = string.replace(/(^')|('$)|('(?=.*)(?=\s))/g, "\"").replace(/(?: '(?=.*))/g, " \"");
return actionReplace
}
console.log(replaceQuotes(text))
Upvotes: 2