1.21 gigawatts 1.21 gigawatts - 5 days ago 7
Javascript Question

How to get an array of attributes when there is whitespace characters between the name and value?

I'm trying to get an array of attributes and I'm splitting on the whitespace character. What I have works fine except when namespaces are involved. Here is my sample code:

XML:

<?xml version="1.0" encoding="utf-8"?>
<s:node something xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:b='testnamespace.com' xmlns="noprefix.com"></something>


Exmascript:

var xmlString:String = 'something xmlns:s = "library://ns.adobe.com/flex/spark" xmlns:b='testnamespace.com' xmlns="noprefix.com"';
var attributes:Array = xmlString.split(/\s+/g);


That results in this array of items:

- something
- xmlns:s
- =
- "library://ns.adobe.com/flex/spark"
- xmlns:b='testnamespace.com'
- xmlns="noprefix.com"


How would I split the attributes up when there are spaces between the name and value?

PS:

I have an XML parser but it throws an error because of mismatched namespaces. So I have to parse the attributes and remove or fix invalid namespaces and then I can pass it the XML string.

PSS:

I only need to work with the first tag to add the namespaces. I'm not doing any other string manipulations.

Answer

Regex for your split, with negative lookahead:

split(/\s+(?!=|"|')/g

Result:

Array[4]
0:"something"
1:"xmlns:s = "library://ns.adobe.com/flex/spark""
2:"xmlns:b="testnamespace.com""
3:"xmlns="noprefix.com""
Comments