1

Assume I have a large string that contains raw svg xml, and I want to change each instance of <path to <path class="pathX" (where X is the index of the matched item). What's the best way to do this in javascript? I'm using this code, which works, but I'm curious if there's a better way:

var svgArray = mySvgStr.split('<path ');
for(var i = 1, len = svgArray.length; i < len; i++) {
  var newStr = 'class="path' + i + '" ' + svgArray[i];
  svgArray[i] = newStr;
}
var svgWithClasses = svgArray.join('<path ');
2
  • 1
    You can use XmlDOM to parse and add the attribute Commented Feb 21, 2014 at 22:46
  • @stackErr is correct - don't parse the string - use an XML parser and modify things that way. You should be able to stringify the document once done Commented Feb 21, 2014 at 22:49

4 Answers 4

6

What about parsing the XML string and using a DOM representation instead? With jQuery:

doc = $.parseXML(xmlString);

Without jQuery:

var parser = new DOMParser();
var doc = parser.parseFromString(xmlString);

Then you can do stuff like this:

var paths = doc.getElementsByTagName('path');
// add attributes here

This is a much less error prone approach.

Sign up to request clarification or add additional context in comments.

Comments

3

Using XmlDOM and XPath:

    xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); \\Create new XML Doc
    xmlDoc.async = "false";
    xmlDoc.loadXML(mySvgStr); \\Load your XML into the Doc


    var pathNodes = xmlDoc.selectNodes("path");
    var count = 1;
    for(count; count < pathNodes.length + 1; count++){
        pathNodes[count-1].setAttribute("class", "path" + count);
    }

Comments

0

Bill F's solution is great, in fact it protects against literal strings, etc, but if you want to keep it simple without XML conversions, you could:

var i = 0;
a = mySvgStr.replace(/<path /g, function (match) {
    return '<path class="path"' + i;
    i++;
});

Comments

0

You can just replace the occurances in the string and use a function to supply the values to replace with:

var i = 1;
mySvgStr = mySvgStr.replace(/<path/g, function(){
  return '<path class="path' + (i++) + '"';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.