我正在使用 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/