RegExp как заменить одинарные кавычки на двойные в этом примере - PullRequest
1 голос
/ 02 мая 2020

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"

Ответы [ 2 ]

2 голосов
/ 02 мая 2020

для " символов \ ставится перед ним.

Так что вы можете просто изменить "#" на "\""

или вы можете изменить "#" на '"'

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))
1 голос
/ 02 мая 2020

В последнем чередовании у вас есть пробел, который не заменяется.

Просто добавьте этот пробел в заменяющую часть, для этого я удалил все ваши бесполезные группы (которые замедляют процесс) и создайте еще один, содержащий место для хранения.

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"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...