javascript - 识别两个子串是否相邻的有效方法

标签 javascript node.js string typescript

我正在使用 JavaScript/TypeScript 开发 NodeJS 应用程序。我正在使用正则表达式搜索文本 block ,所以我有一个匹配数组。我想要一种简洁的方法来识别这些字符串是否相邻,除了一些可能的空格之外。

所以我当前的应用程序是这样的。我正在渲染 markdown,如果有两个代码块,一个紧接着另一个,我想将它们渲染为选项卡式代码块。

for (let codeBlock of codeBlocks) {
    var title = /```\s?(.*?\n)/.exec(codeBlock);
    var code = /```.*([\s\S]*?)```/g.exec(codeBlock)[1];
    //console.log('Code: ' + code);
    //console.log('Title: ' + title[1]);
    result.push(code, title[1]);
    var startPos = content.indexOf(code);
    var containsSomething = new RegExp('/[a-z]+/i');
   //if the string between the end of the last code block and the start of this one contains any content
    if (containsSomething.test(content.substring(startPos, lastEndPos))) {
        result.push('n'); // Not a tabbed codeblock
    } else {
        result.push('y'));  //Is a tabbed codeblock
    }
    lastEndPos = code.length + startPos + title[1].length + 6;
    results.push(result);
    result = [];
}

因此,在下面的示例输入中,我需要区分应该使用选项卡的前两个代码块和不应该使用选项卡的第三个代码块。

``` JavaScript                       //in the code example above, this would be the title
    var something = new somethingelse();     //in the code example above, this would be the code
```
``` CSS
.view {
    display: true;
}
```
Some non-code text...

``` html
<div></div>
```

最佳答案

使用RegExp.escape (polyfill)您可以将字符串转换为 RegExp-safe 版本,然后创建一个将它们与变量空格匹配的表达式,

let matches = ['foo', 'bar'];
let pattern = matches.map(RegExp.escape).join('\\s*'); // "foo\\s*bar"
let re = new RegExp(pattern); // /foo\s*bar/

现在可以将其应用到您的干草堆中;

re.test('foo\n\n\nbar'); // true
re.test('foo\nbaz\n\nbar'); // false

关于javascript - 识别两个子串是否相邻的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38778514/

相关文章:

javascript - NodeJS、Google 日历 API 集成未经过身份验证并返回未定义,无论凭证和 token 是否存在

node.js - Nodemailer 和 ical-generator - 发送日历邀请

c - 为什么下面的代码给出了垃圾值?

node.js - 如何使用Nodejs Express获取发送请求的客户端的公共(public)IP地址?

c - 在 C 中解压缩 .gz 字符串?

java - mirrorEnds 谜题没有给出任何错误线索

javascript - 将类绑定(bind)到另一个类的实例

javascript - 如何在 django 模板中设置变量(使用 set 标签)?

javascript - 展开/折叠 HTML 中的文本 - Javascript

node.js - socket.io-redis 如何在幕后工作?