JavaScript / ECMAScript

XML Namespace Declaration in JS

Match XML namespace declarations (`xmlns="..."` and `xmlns:prefix="..."`), capturing the prefix and URI.

Try it in the JS tester →

Pattern

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

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("xmlns(?::([\\w\\-]+))?\\s*=\\s*[\"']([^\"']+)[\"']", "g");
const input = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">";
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

xmlns matches the literal attribute name. (?::([\w\-]+))? optionally captures a colon-prefix (e.g. `xmlns:xlink`). \s*=\s* matches the equals with optional whitespace. ["']([^"']+)["'] captures the URI in either quote style.

Examples

Input

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

Matches

  • xmlns="http://www.w3.org/2000/svg"
  • xmlns:xlink="http://www.w3.org/1999/xlink"

Input

<root xmlns='urn:custom'>

Matches

  • xmlns='urn:custom'

Input

<plain>

No match

Same pattern, other engines

← Back to XML Namespace Declaration overview (all engines)