@@ -70,6 +70,10 @@ export interface IRenderOptions extends IRendererOptionsIn {
7070}
7171
7272export const addPrefix = ( svg : string , opts = { } as IRenderOptions ) : string => {
73+ const escapeRegex = ( str : string ) : string => {
74+ return str . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, "\\$&" ) ;
75+ }
76+
7377 if ( opts . prefix !== undefined ) {
7478 const prefix = opts . prefix ;
7579 // Regex to find all id="something"
@@ -85,21 +89,22 @@ export const addPrefix = (svg: string, opts = {} as IRenderOptions): string => {
8589 // For each ID, replace both the definition and references
8690 ids . forEach ( ( id ) => {
8791 const newId = `${ prefix } ${ id } ` ;
92+ const escapedId = escapeRegex ( id ) ;
8893
8994 // Replace the id definition
90- const idDefRegex = new RegExp ( `id="${ id } "` , "g" ) ;
95+ const idDefRegex = new RegExp ( `id="${ escapedId } "` , "g" ) ;
9196 svg = svg . replace ( idDefRegex , `id="${ newId } "` ) ;
9297
9398 // Replace references: url(#id), href="#id", xlink:href="#id"
9499 const refPatterns = [
95- new RegExp ( `url\\(#${ id } \\)` , "g" ) ,
96- new RegExp ( `href="#${ id } "` , "g" ) ,
97- new RegExp ( `xlink:href="#${ id } "` , "g" ) ,
98- new RegExp ( `"#${ id } "` , "g" ) , // handles cases like begin="0s;id.end"
100+ new RegExp ( `url\\(#${ escapedId } \\)` , "g" ) ,
101+ new RegExp ( `href="#${ escapedId } "` , "g" ) ,
102+ new RegExp ( `xlink:href="#${ escapedId } "` , "g" ) ,
103+ new RegExp ( `"#${ escapedId } "` , "g" ) , // handles cases like begin="0s;id.end"
99104 ] ;
100105
101106 refPatterns . forEach ( ( regex ) => {
102- svg = svg . replace ( regex , ( match ) => match . replace ( `#${ id } ` , `#${ newId } ` ) ) ;
107+ svg = svg . replace ( regex , ( match ) => match . replace ( `#${ id } ` , `#${ newId } ` ) ) ;
103108 } ) ;
104109 } ) ;
105110 }
0 commit comments