我正在try 解析一个与下面的字符串类似的字符串.这表示对一本书的查询.有多个选项可用于查找特定字段,因此intitle:专门在书名中查找内容.我有两个问题.

  1. 它没有解析出第三个返回元素中的一些术语,如inAuthor和inPublisher-‘Champ inAuthor:"John Smith"inPublisher:"the book Place"’-这可能与字符串中的双引号有关?
  2. 我如何使用双引号使其成为单任期?

JSFiddle example

字符串:

basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156

我的try

let q: string = `basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156`;
console.log(q);
q = q.replaceAll(`: `, `:`);
console.log(q);
let all = q.split(
  /(\bintitle:\b|\binauthor:\b|\binpublisher:\b|\bsubject:\b|\bisbn:\b|\blccn:\b|\boclc:\b)/,
);
console.log(all);
[
  'basketball ',
  'intitle:',
  'champ inauthor:"john smith" inpublisher:"the book place" ',
  'subject:',
  'fiba ',
  'isbn:',
  '12345 ',
  'lccn:',
  '689778 ',
  'oclc:',
  '1234156'
]

推荐答案

如果搜索词可以以不同的字符开头/结尾,则可以在此处使用自适应单词边界:

let q: string = `basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156`;
q = q.replaceAll(`: `, `:`);

let terms = ['intitle:', 'inauthor:', 'inpublisher:', 'subject:', 'isbn:', 'lccn:', 'oclc:'];
let regex: RegExp = new RegExp(String.raw`(?!\B\w)(${terms.map(x => x.replace(/[\/\-\\^$*+?.()|[\]{}]/g, '\\$&')).join('|')})(?!\B\w)`);

let all = q.split(regex);
console.log(all);

正则表达式将如下所示

/(?!\B\w)(intitle:|inauthor:|inpublisher:|subject:|isbn:|lccn:|oclc:)(?!\B\w)/

其中,如果单词的开始/结束处的字符是单词字符,则(?!\B\w)将仅需要单词边界.

如果有任何特殊的正则表达式元字符,则terms.map(x => x.replace(/[\/\-\\^$*+?.()|[\]{}]/g, '\\$&')).join('|')部分将避开搜索terms.

Javascript相关问答推荐

二维数组,过滤并返回带有索引而不是值的新数组

HTML/JavaScript函数未执行

如何在NightWatch.js测试中允许浏览器权限?

具有相同参数的JS类

单击更新页面的按钮后,页面刷新;测试/断言超时,有两个标题,但没有一个标题

如何使用侧边滚动按钮具体滚动每4个格?

字节数组通过echo框架传输到JS blob

colored颜色 检测JS,平均图像 colored颜色 检测JS

构造HTML表单以使用表单数据创建对象数组

如何从URL获取令牌?

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

编辑文本无响应.onClick(扩展脚本)

如何在ASP.NET项目中使用Google Chart API JavaScript将二次轴线值格式化为百分比

当输入字段无效时,我的应用程序不会返回错误

使用getBorbingClientRect()更改绝对元素位置

钛中的onClick事件需要在两次点击之间等待几秒钟

按下单键和多值

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

Cherrio JS返回父div的所有图像SRC