且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

双引号之间的 JavaScript 文本

更新时间:2023-02-20 08:15:34

尝试:

<script>
let str1 = 'Neque porro quisquam est qui dolorem ipsum';
let str2 = 'Neque "porro quisquam est" qui dolorem ipsum';
let str3 = 'Neque "porro';
let str4 = 'Neque "porro" quisquam "est" qui dolorem ipsum';

function extractFirstText(str){
  const matches = str.match(/"(.*?)"/);
  return console.log(matches
    ? matches[1]
    : str);
}


function extractAllText(str){
  const re = /"(.*?)"/g;
  const result = [];
  let current;
  while (current = re.exec(str)) {
    result.push(current.pop());
  }
  return console.log(result.length > 0
    ? result
    : [str]);
}

// Execution of the functions

extractFirstText(str1);
//Neque porro quisquam est qui dolorem ipsum

extractFirstText(str2);
//porro quisquam est

extractFirstText(str3);
//Neque "porro

extractFirstText(str4);
//porro

extractAllText(str1);
//Array [ "Neque porro quisquam est qui dolorem ipsum" ]

extractAllText(str2);
//Array [ "porro quisquam est" ]

extractAllText(str3);
//Array [ "Neque "porro" ]

extractAllText(str4);
//Array [ "porro", "est" ]
</script>

EDIT 重新设计以同时考虑@AshishMaity 评论中关于匹配多个子字符串的废弃编辑,以及@JosephCho 评论关于原始中断以防有单引号(str3 中的以上案例)

EDIT reworked to take into account both @AshishMaity comment in a discarded edit about matching more than one substring, and @JosephCho comment about the original breaking in case there is a single quote (str3 in the case above)