const regex = /(?<!\\) # Check it was not escaped with a \
(?<img_all>
\!\[(?<img_alt>.+?)\] # image alternative text, i.e. the text used when the image does not
(?:
(?:
[ ]? # possibly followed by some spaces
(?:\n[ ]*)? # and a new line with some space
\[(?<img_id>.*?)\] # with the link id in brackets, but may be empty
)
|
(?:
(?:
\(
[ \t]*
<(?<img_url> # link url within <>; or
.+?
)>
[ \t]* # possibly followed by some spaces or tabs
(?:
(?<img_title_container>['"]) # Title is surrounded ether by double or single quotes
(?<img_title>.*?) # actual title, but could be empty as in ""
\g{img_title_container} # make the sure enclosing mark balance
)?
[ \t]*
\)
)
|
(?:
\(
[ \t]*
(?<img_url> # link url within <>; or
(?:((?!["']).)*+|.*)
)
[ \t]*
(?:
(?<img_title_container>['"]) # Title is surrounded ether by double or single quotes
(?<img_title>.*?) # actual title, but could be empty as in ""
\g{img_title_container} # make the sure enclosing mark balance
)?
[ \t]*
\)
)
)
)
)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<!\\\\) # Check it was not escaped with a \\
(?<img_all>
\\!\\[(?<img_alt>.+?)\\] # image alternative text, i.e. the text used when the image does not
(?:
(?:
[ ]? # possibly followed by some spaces
(?:\\n[ ]*)? # and a new line with some space
\\[(?<img_id>.*?)\\] # with the link id in brackets, but may be empty
)
|
(?:
(?:
\\(
[ \\t]*
<(?<img_url> # link url within <>; or
.+?
)>
[ \\t]* # possibly followed by some spaces or tabs
(?:
(?<img_title_container>[\'"]) # Title is surrounded ether by double or single quotes
(?<img_title>.*?) # actual title, but could be empty as in ""
\\g{img_title_container} # make the sure enclosing mark balance
)?
[ \\t]*
\\)
)
|
(?:
\\(
[ \\t]*
(?<img_url> # link url within <>; or
(?:((?!["\']).)*+|.*)
)
[ \\t]*
(?:
(?<img_title_container>[\'"]) # Title is surrounded ether by double or single quotes
(?<img_title>.*?) # actual title, but could be empty as in ""
\\g{img_title_container} # make the sure enclosing mark balance
)?
[ \\t]*
\\)
)
)
)
)', 'gm')
const str = `
Inline within a paragraph: .
.jpg'Title here')
.jpg "With title") some text after

`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions