/ walking bear:D / JS note 使用 regex 改變單雙引號

JS note 使用 regex 改變單雙引號

2019-10-04 posted in [筆記]

eloquent javascript 的練習題 : 將字串對話 'I'm the cook,' he said, 'it's my job.' 其中的單引號改成雙引號,但略過縮讀字 contraction 的單引號,如: I'm 或者 It's

修改來幾次還是不得其解,偷看了這篇 gist ,修改出答案:

let text = "'I'm the cook,' he said, 'it's my job.'";
console.log(`${text} →`);
// → "I'm the cook," he said, "it's my job."
console.log(text.replace(/(^)'|(\W)'|'(\W)|'($)/g, '$2"$3'));

submatch $1, $2, $3 是根據 regex 字串的左小括弧出現的順序決定,其中是否出現符號 | 無關,這是我做了習題才弄清楚的概念 . reply_count: 0 get_replies : 0 .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll