sketch-hq/SketchAPI

Regex broken when using quotes and/or doublequotes

cmcculloh-kr opened this issue · 0 comments

Take the following valid JS:

const dom = require('sketch/dom');
const doc = dom.getSelectedDocument();
const targetName = "arbitraryName";
const newName = "arbitraryNewName";
const targetLayers = doc.getLayersNamed(targetName);
targetLayers.forEach(layer => layer.name = newName.replace(/['"]/, ''));

Sketch breaks when you try and run it (you get the following):

SyntaxError: Unexpected end of script
    at /Users/cmcculloh/Library/Application Support/com.bohemiancoding.sketch3/Plugins/Untitled.sketchplugin:7
Script executed in 5.573034s

So you have to double up the quotes, like this:

const dom = require('sketch/dom');
const doc = dom.getSelectedDocument();
const targetName = "arbitraryName";
const newName = "arbitraryNewName";
const targetLayers = doc.getLayersNamed(targetName);
targetLayers.forEach(layer => layer.name = newName.replace(/[''""]/, ''));

Note that this is just simplified example code that (yes I recognize) makes no sense (why would you want to run a replace on newName instead of just giving it the right name?), and is merely mean to illustrate the brokenness of Sketch's JS RexExp engine. My actual code is part of a plugin that, among other things, validates/fixes all layer names (removing spaces, em & en dashes, etc).