Oh how strange! I'm embarrassed to say I never actually tried that simplified code I posted (and yes, it works for me too).
It looks like the actual problem had something to do with what I assume is a bug with Sketch's JS RegExp. 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).
Thank you for your answer! My code is now working 🙂