本文介绍了双引号之间的 JavaScript 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to get the text between double quotes using JavaScript. I found online something like title.match(/".*?"/); but the thing is that sometimes I have text between double quotes but sometimes there are no quotes. What I am saying is that sometimes I receive strings like: Neque porro quisquam est qui dolorem ipsum and sometimes strings like: Neque "porro quisquam est" qui dolorem ipsum. The thing is, when I have text containing double quotes I want to retrieve the text between them but when they aren't present, I'd like the whole text.Also I have observered that string.indexOf(""") does not work and I don't really know how to approach this problem. Thanks.

推荐答案

尝试:

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

这篇关于双引号之间的 JavaScript 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 01:05