@@ -55,9 +55,13 @@ export default class N3Writer {
5555 if ( ! ( / t r i p l e | q u a d / i) . test ( options . format ) ) {
5656 this . _lineMode = false ;
5757 this . _graph = DEFAULTGRAPH ;
58- this . _baseIRI = options . baseIRI ;
5958 this . _prefixIRIs = Object . create ( null ) ;
6059 options . prefixes && this . addPrefixes ( options . prefixes ) ;
60+ if ( options . baseIRI ) {
61+ this . _baseMatcher = new RegExp ( `^${ escapeRegex ( options . baseIRI )
62+ } ${ options . baseIRI . endsWith ( '/' ) ? '' : '[#?]' } `) ;
63+ this . _baseLength = options . baseIRI . length ;
64+ }
6165 }
6266 else {
6367 this . _lineMode = true ;
@@ -148,8 +152,8 @@ export default class N3Writer {
148152 }
149153 let iri = entity . value ;
150154 // Use relative IRIs if requested and possible
151- if ( this . _baseIRI && iri . startsWith ( this . _baseIRI ) )
152- iri = iri . substr ( this . _baseIRI . length ) ;
155+ if ( this . _baseMatcher && this . _baseMatcher . test ( iri ) )
156+ iri = iri . substr ( this . _baseLength ) ;
153157 // Escape special characters
154158 if ( escape . test ( iri ) )
155159 iri = iri . replace ( escapeAll , characterReplacer ) ;
@@ -290,7 +294,7 @@ export default class N3Writer {
290294 IRIlist += IRIlist ? `|${ prefixIRI } ` : prefixIRI ;
291295 prefixList += ( prefixList ? '|' : '' ) + this . _prefixIRIs [ prefixIRI ] ;
292296 }
293- IRIlist = IRIlist . replace ( / [ \] \/ \( \) \* \+ \? \. \\ \$ ] / g, '\\$&' ) ;
297+ IRIlist = escapeRegex ( IRIlist , / [ \] \/ \( \) \* \+ \? \. \\ \$ ] / g, '\\$&' ) ;
294298 this . _prefixRegex = new RegExp ( `^(?:${ prefixList } )[^\/]*$|` +
295299 `^(${ IRIlist } )([a-zA-Z][\\-_a-zA-Z0-9]*)$` ) ;
296300 }
@@ -389,3 +393,7 @@ function characterReplacer(character) {
389393 }
390394 return result ;
391395}
396+
397+ function escapeRegex ( regex ) {
398+ return regex . replace ( / [ \] \/ \( \) \* \+ \? \. \\ \$ ] / g, '\\$&' ) ;
399+ }
0 commit comments