Can I make an existing script (for replacing text in layer names) loop only through selected layers?
Hello, comunity.
A while back, I have found the script below on this forum, courtesy of @Inventsable. It's function is to batch rename layers based on replacing an existing string with another input string. I have modified this script a little bit for personal use, making sure that the string I want to replace is captured through a prompt inside Illustrator, as oposed to the original which was hard-coded.
I'm not much of a coder, so my question now is this: Is it possible to modify this script in a way that will allow it to work only on layers that have been selected?
Looking forward to hearing your thoughts!
// You can change these settings:
var settings = {
// Should the script guess the name for unnamed items like <Group>, <Path>, etc:
replaceGenerics: true,
// Should the script replace "HELLO" when findText is "Hello":
caseSensitive: false
}
var findText = Window.prompt ('Enter Search String', 'text 1', 'Find/Replace Layer Names');
if (findText == null) {
alert ('Cancelled by user');
}
var replaceText = Window.prompt ('Enter Replace String', 'text 2', 'Find/Replace Layer Names');
if (replaceText == null) {
alert ('Cancelled by user');
}
/**
*
* Don't edit below unless you know what you're doing
*
*/
Array.prototype.forEach = function (callback) {
for (var i = 0; i < this.length; i++) callback(this[i], i, this);
};
function get(type, parent) {
if (arguments.length == 1 || !parent) parent = app.activeDocument;
var result = [];
if (!parent[type]) return [];
for (var i = 0; i < parent[type].length; i++) {
result.push(parent[type][i]);
if (parent[type][i][type])
result = [].concat(result, get(type, parent[type][i]));
}
return result || [];
}
function findReplace(find, replace, options) {
var layers = get('layers');
var pageItems = get('pageItems');
var list = [].concat(layers, pageItems);
var findRX = new RegExp(getEscapedRXString(find), !options.caseSensitive ? 'i' : null)
list.forEach(function (item) {
if (item.name.length)
item.name = item.name.replace(findRX, replace)
else
item.name = options.replaceGenerics && findRX.test(item.typename)
? item.typename.replace(/item/i, '').replace(findRX, replace)
: item.name
})
}
function getEscapedRXString(string) {
return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
}
findReplace(findText, replaceText, settings)