George Edwards George Edwards - 5 months ago 24
TypeScript Question

Efficient means of identifying if two substrings are adjacent

I am working on a nodeJS application in JavaScript/TypeScript. I am searching a block of text with a regex, so I have an array of matches. I want a neat way of identifying if these strings are adjacent, except for some possible whitespace.

So my current application is this. I am rendering markdown, and if there are two code blocks, one immediately after the other, I want to render them as a tabbed code block.

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;
result = [];

So in the example input below, I need to discern between the top two code blocks which should be tabbed and the third one which shouldn't be.

``` 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


Using RegExp.escape (polyfill) you could convert your strings into RegExp-safe versions, then create an expression which would match them with variable whitespace,

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

Now can apply this to your haystack;

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