如何在Node.js中提取字符串内转义双引号(")中的内容
嘿,这个需求在Node.js开发里挺常见的,我给你分享两个实用的实现方法,直接就能用:
方法1:正则表达式(最简洁高效)
正则是处理这类字符串提取的首选,我们可以写一个匹配"包裹内容的规则,用非贪婪模式避免匹配到多余的内容:
var information = 'Hello "beautiful and amazing" world.'; // 匹配被"包裹的内容,非贪婪模式确保只取中间部分 const regex = /"(.*?)"/; const matchResult = information.match(regex); // 加个判断避免没有匹配到的情况报错 const result = matchResult ? matchResult[1] : ''; console.log(result); // 输出: beautiful and amazing
如果你的字符串里有多个被"包裹的内容,比如'Hello "first" and "second" world.',可以加上全局修饰符g,循环提取所有结果:
var information = 'Hello "first" and "second" world.'; const regex = /"(.*?)"/g; const results = []; let match; while ((match = regex.exec(information)) !== null) { results.push(match[1]); } console.log(results); // 输出: ['first', 'second']
方法2:字符串分割法(适合不想用正则的场景)
如果对正则不太熟悉,用字符串分割也能轻松搞定。思路是把字符串按"拆分成数组,中间的内容正好是数组的第二个元素:
var information = 'Hello "beautiful and amazing" world.'; const parts = information.split('"'); // 同样加个边界判断,防止数组长度不够 const result = parts.length >= 2 ? parts[1] : ''; console.log(result); // 输出: beautiful and amazing
要是有多个包裹内容的话,只需要遍历分割后的数组,取奇数索引的元素(从0开始数,1、3...都是我们要的内容):
var information = 'Hello "first" and "second" world.'; const parts = information.split('"'); const results = []; for (let i = 1; i < parts.length; i += 2) { results.push(parts[i]); } console.log(results); // 输出: ['first', 'second']
小提示
如果遇到"前后有多余空格的情况,比如'Hello " beautiful world "',可以在正则里加上\s*来忽略空格:
const regex = /"\s*(.*?)\s*"/;
这样提取出来的内容就不会带前后空格啦~
内容的提问来源于stack exchange,提问作者giorgosempiros
相关产品推荐
相关产品推荐

