Check if a string is SVG
npx @tessl/cli install tessl/npm-is-svg@6.1.0is-svg provides a lightweight utility function for detecting whether a given string contains valid SVG (Scalable Vector Graphics) content. It performs XML validation and specifically identifies SVG format through proper XML parsing with configurable validation options.
npm install is-svgimport isSvg from 'is-svg';This package requires Node.js 20+ and only provides ES module exports.
import isSvg from 'is-svg';
// Basic SVG detection
isSvg('<svg xmlns="http://www.w3.org/2000/svg"><path fill="#00CD9F"/></svg>');
//=> true
isSvg('<div>Not SVG</div>');
//=> false
// Performance mode with reduced validation
isSvg('<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>', {validate: false});
//=> true
// Full validation mode (default)
isSvg('<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>', {validate: true});
//=> trueChecks if a string contains valid SVG content using XML validation.
/**
* Check if a string is SVG
* @param string - The input string to check for SVG content
* @param options - Configuration options
* @returns true if the string contains valid SVG, false otherwise
* @throws TypeError if first argument is not a string
*/
function isSvg(string: string, options?: Options): boolean;
interface Options {
/**
* Whether to validate the SVG as proper XML.
* Turning this off can improve performance significantly.
* @default true
*/
validate?: boolean;
}Behavior:
TypeError if the first argument is not a stringfalse for empty stringstrue if the string contains valid SVG, false otherwisePerformance Considerations:
validate: false improves performance significantly by using chunked processingvalidate: true (default) provides thorough XML validation for accuracyUsage Examples:
import isSvg from 'is-svg';
// Valid SVG examples
isSvg('<svg xmlns="http://www.w3.org/2000/svg"></svg>');
//=> true
isSvg('<svg><rect width="100" height="100"/></svg>');
//=> true
// Invalid examples
isSvg('<div>Not an SVG</div>');
//=> false
isSvg('');
//=> false
isSvg(' ');
//=> false
// Error handling
try {
isSvg(123); // TypeError: Expected a `string`, got `number`
} catch (error) {
console.error(error.message);
}
// Performance optimization for large files
const largeSvgString = '...'; // Large SVG content
const isValidSvg = isSvg(largeSvgString, {validate: false}); // Faster processingThe function throws a TypeError when the first argument is not a string:
// This will throw: TypeError: Expected a `string`, got `number`
isSvg(123);
// This will throw: TypeError: Expected a `string`, got `undefined`
isSvg();For all other cases (invalid XML, non-SVG content, empty strings), the function returns false rather than throwing errors.