From a69384113db9bd2922366e991567916ccdbddc4b Mon Sep 17 00:00:00 2001 From: Kyriakos Ziakoulis Date: Mon, 13 May 2019 17:30:26 +0300 Subject: [PATCH] Fix: idPrefix regex to support style attr Currently createIdPrefix for tag attributes only works if the url is the first value. e.g: This commit adds support also for the following. --- lib/transformer.js | 15 +++++++++++---- tests/fixtures/with-ids.svg | 2 +- tests/svg-inline-loader.test.js | 5 ++--- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/transformer.js b/lib/transformer.js index cef721d..c92fcad 100644 --- a/lib/transformer.js +++ b/lib/transformer.js @@ -131,7 +131,7 @@ function createClassPrefix(classPrefix) { } function createIdPrefix(idPrefix) { - var url_pattern = /^url\(#.+\)$/i; + var url_pattern = /url\(#.+?\)/i; return function prefixIds(tag) { var idIdx = getAttributeIndex(tag, 'id'); if (idIdx !== -1) { @@ -150,10 +150,17 @@ function createIdPrefix(idPrefix) { if (tag.attributes && tag.attributes.length > 0) { // replace instances of url(#foo) in attributes tag.attributes.forEach(function (attr) { - if (attr[1].match(url_pattern)) { + var attrValue = attr[1].match(url_pattern); + if (attrValue) { attr[1] = attr[1].replace(url_pattern, function (match) { - var id = match.substring(5, match.length -1); - return "url(#" + idPrefix + id + ")"; + var index = attr[1].indexOf(attrValue[0]); + var id = match.substring(5, match.length - 1) + return ( + attr[1].slice(index, index + 5) + + idPrefix + + id + + attr[1].slice(index + 5 + id.length) + ) }); } diff --git a/tests/fixtures/with-ids.svg b/tests/fixtures/with-ids.svg index 822b61c..3e4f286 100644 --- a/tests/fixtures/with-ids.svg +++ b/tests/fixtures/with-ids.svg @@ -3,7 +3,7 @@ - + diff --git a/tests/svg-inline-loader.test.js b/tests/svg-inline-loader.test.js index 676440c..6f9c785 100644 --- a/tests/svg-inline-loader.test.js +++ b/tests/svg-inline-loader.test.js @@ -56,12 +56,11 @@ describe('getExtractedSVG()', function(){ var svgWithStyle = require('raw!./fixtures/with-ids.svg'); var processedStyleInsertedSVG = SVGInlineLoader.getExtractedSVG(svgWithStyle, { idPrefix: 'test.prefix-' }); - - assert.isTrue( processedStyleInsertedSVG.match(/test\.prefix-foo/g).length === 3 ); + assert.isTrue( processedStyleInsertedSVG.match(/test\.prefix-foo/g).length === 4 ); // // replaces xlink:href= assert.isTrue( processedStyleInsertedSVG.match(/xlink:href=/g).length === 1 ); // // replaces url(#foo) - assert.isTrue( processedStyleInsertedSVG.match(/url\(#test\.prefix-foo\)/g).length === 1 ); + assert.isTrue( processedStyleInsertedSVG.match(/url\(#test\.prefix-foo\)/g).length === 2 ); }); it('should be able to specify tags to be removed by `removingTags` option', function () {