如何使用JavaScript从段落提取引号内对话并存储到数组
用JavaScript提取段落中引号包裹的对话并存入数组
嘿,这个需求其实挺常见的,尤其是处理文本内容的时候。我来给你分享两种靠谱的实现方式,核心都是用正则表达式来精准匹配引号里的内容:
方法一:用exec循环遍历匹配(兼容旧环境)
这种方式适配所有JavaScript运行环境,包括一些版本较老的浏览器:
var myParagraph = ' “Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?” “Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.” “I know nothing about him,” I murmur, trying and failing to suppress my rising panic. “The questions will see you through. Go. It’s a...'; // 正则说明:匹配中文左引号“,捕获中间所有非右引号”的内容,直到遇到右引号 const quoteRegex = /“([^”]*)”/g; const dialogues = []; let matchResult; // 循环执行exec,直到没有新的匹配结果 while ((matchResult = quoteRegex.exec(myParagraph)) !== null) { // matchResult[1]是捕获到的引号内内容,trim()去掉前后可能的冗余空格 dialogues.push(matchResult[1].trim()); } console.log(dialogues);
运行后会得到整理好的对话数组:
[
"Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?",
"Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.",
"I know nothing about him,"
]
方法二:用matchAll简化代码(ES6+)
如果你的项目支持ES6及以上语法,用matchAll能让代码更简洁优雅:
var myParagraph = ' “Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?” “Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.” “I know nothing about him,” I murmur, trying and failing to suppress my rising panic. “The questions will see you through. Go. It’s a...'; const quoteRegex = /“([^”]*)”/g; // 用matchAll获取所有匹配结果,转成数组后提取捕获组内容 const dialogues = Array.from(myParagraph.matchAll(quoteRegex)).map(item => item[1].trim()); console.log(dialogues);
额外适配:同时支持中英文引号
如果你的段落里混合了中文引号“”和英文引号"",可以把正则改成下面这样,同时匹配两种引号格式:
const quoteRegex = /["“]([^"”]*)["”]/g;
⚠️ 注意:如果文本里出现嵌套引号的极端情况(比如"He said: "Hello""),这个正则会失效,但日常对话类文本里几乎不会遇到这种场景,所以这个方案足够应付绝大多数需求。
内容的提问来源于stack exchange,提问作者Pep
相关产品推荐
相关产品推荐

