dan
dan

Reputation: 1984

Javascript regex to find a particular string which could be broken across multiple lines

I'm trying to write a regex which gets a particular substring from a string. However, the substring could be broken across multiple lines.

I've tried using the multiline flag, like this:

"foo\nbar".match(/foobar/m)

But that returns null.

I've also seen a number of posts suggesting I use [\S\s]. However, as far as I can tell, this only works if you know where the break line will be, like this:

'foo\nbar'.match(/foo[\S\s]bar/m)

Is there a way to find all instaces of foobar in a string when the line break could anywhere in the string?

Upvotes: 2

Views: 123

Answers (1)

anubhava
anubhava

Reputation: 785276

Is there a way to find all instances of foobar in a string when the line break could anywhere in the string?

Remove all line-breaks from subject before comparing with your regex.

See this simple demo:

const arr = ["foo\nbar", "\nfoobar", "fo\nobar", "foobar\n", "foobar"];

const val = 'foobar';

arr.forEach(function(el) {
   console.log(el.replace(/\n/, '') == val)
});

Upvotes: 1

Related Questions