18

我想使用 JavaScript 获取双引号之间的文本。我在网上找到了类似title.match(/".*?"/);的东西,但问题是有时我在双引号之间有文字,但有时没有引号。我要说的是,有时我会收到类似的字符串:Neque porro quisquam est qui dolorem ipsum有时会收到类似的字符串:Neque "porro quisquam est" qui dolorem ipsum。问题是,当我有包含双引号的文本时,我想检索它们之间的文本,但是当它们不存在时,我想要整个文本。我也观察到string.indexOf("\"")这不起作用,我真的不知道如何解决这个问题。谢谢。

4

4 回答 4

40

尝试:

<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>

编辑重新设计以考虑@AshishMaity 注释中关于匹配多个子字符串的废弃编辑,以及@JosephCho 关于原始中断的注释以防有单引号(上述情况下为str3)

于 2013-11-05T16:05:39.193 回答
18

试试这个:

/"((?:\\.|[^"\\])*)"/

正则表达式可视化

调试演示

于 2013-11-05T16:05:55.137 回答
9

在单个正则表达式中:

var m = s.match(/(?:"[^"]*"|^[^"]*$)/)[0].replace(/"/g, "");

测试:

s = 'Neque "porro quisquam est" qui dolorem ipsum';
m = s.match(/(?:"[^"]*"|^[^"]*$)/)[0].replace(/"/g, "");
//=> porro quisquam est

s = 'Neque porro quisquam est qui dolorem ipsum';
m = s.match(/(?:"[^"]*"|^[^"]*$)/)[0].replace(/"/g, "");
//=> Neque porro quisquam est qui dolorem ipsum
于 2013-11-05T16:08:13.870 回答
2

split() 函数可用于获取双引号中的值

let str1 = 'Neque "porro quisquam est" qui dolorem ipsum';
let str2 = 'Neque porro quisquam est qui dolorem ipsum';

function findFirstOccurance(str){
  const matches = str.split('"');
  return matches[1] ? matches[1] : str;
}


console.log(findFirstOccurance(str1));
console.log(findFirstOccurance(str2)); 

于 2018-08-27T11:52:31.107 回答