JavaScript / ECMAScript

XML Processing Instruction in JS

Match XML processing instructions like `<?xml version="1.0" encoding="utf-8"?>` or `<?xml-stylesheet href="..."?>`.

Try it in the JS tester →

Pattern

regexJS
<\?[\w\-]+(?:\s+[\w\-]+\s*=\s*["'][^"']*["'])*\s*\?>   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("<\\?[\\w\\-]+(?:\\s+[\\w\\-]+\\s*=\\s*[\"'][^\"']*[\"'])*\\s*\\?>", "g");
const input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

<\? matches the literal opener. [\w\-]+ captures the PI target name. The repeating group matches optional `attr="value"` pairs. The trailing `\s*\?>` matches the closer. Works for the XML declaration and any custom processing instruction.

Examples

Input

<?xml version="1.0" encoding="UTF-8"?>

Matches

  • <?xml version="1.0" encoding="UTF-8"?>

Input

<?xml-stylesheet type="text/xsl" href="style.xsl"?>

Matches

  • <?xml-stylesheet type="text/xsl" href="style.xsl"?>

Input

<root>plain</root>

No match

Same pattern, other engines

← Back to XML Processing Instruction overview (all engines)