Skip to main content
Participant
August 12, 2013
Question

Find Replace Script - Style Issue

  • August 12, 2013
  • 1 reply
  • 905 views

I am newbie in Illustrator Scripting.

I wrote a find replace script which looks for specific text in the file and replaces with some given content:

For Example:  AI file has - 'I love my Dad'  and we want to replace Dad with Mom, Uncle etc. using script. Current script works perfectly fine for simple text but if we add Style to part of text like 'I LOVE my DAD' - (Italic LOVE and Bold DAD) the replacement doesn't work...I expect it to be: 'I LOVE my MOM' but the result is - 'I LOVE my MOM' with all style removed.

Current Script

var pageItemRef = document.layers[0].pageItems[0]

                pageItemRef.contents = pageItemRef.contents.replace(replacementText, fileArray[1]);

                replacementText = fileArray[1];

                var myDoc = app.activeDocument

                for (s = 0; s < curStyles.length; s++)

                {

                    var lastStyle = curStyles[ s ];

                    lastStyle.applyTo( document.textFrames[0] );

                }

                var options = new ExportOptionsPNG24();

                var file = new File(folder + "/" + fileArray[0] + ".png");

                document.exportFile(file,ExportType.PNG24,options);

                var file2 = new File(folder + "/" + fileArray[0] + ".ai");

                document.saveAs(file2);

I am not sure if it's possible through script to retain the content styling.

Please can someone urgently suggest a workaround or point me to some article....

This topic has been closed for replies.

1 reply

CarlosCanto
Community Expert
Community Expert
August 13, 2013

here's one way of replacing text preserving formatting

select the text frame with your "I LOVE my DAD" text before running

// carlos canto

// http://forums.adobe.com/message/5589589#5589589

var idoc = app.activeDocument;

var sel = idoc.selection[0];

var searchString = "DAD";

var replaceString = "MOM";

var searchStringLength = searchString.length;

var idx = sel.contents.search (searchString);

if (idx == -1) {

    alert('string not found');

}

else {

    var range = sel.characters[idx];

    range.length = searchStringLength;

    range.contents = replaceString;

}

Participant
August 13, 2013

Champion!!! Really thankful for the guidance and the trick worked. Highly appreciated!!!