Skip to main content
Inspiring
October 4, 2024
Answered

How to remove all the spaces from a text frame?

  • October 4, 2024
  • 1 reply
  • 410 views

There is a text frame in a document. Whete each world is colored by a seprate color. 
I try to remove all the spaces in the frame but there is an error "No such element"

 on the line "var wordRange = textFrame.textRange.characters[charIndex];"

var doc = app.activeDocument;
var textFrame = doc.textFrames[0]; // assume text frame is present

var contents = textFrame.contents;
var words = contents.split(" ");
var colors = [];

var charIndex = 0;
for (var i = 0; i < words.length; i++) {
    var wordLength = words[i].length;
    var wordRange = textFrame.textRange.characters[charIndex];
    wordRange.length = wordLength;
    colors.push(wordRange.fillColor);
    charIndex += wordLength + 1;
}

var newContents = contents.replace(/\s+/g, '');

var newTextFrame = doc.textFrames.add();
newTextFrame.position = textFrame.position;
newTextFrame.contents = newContents;

charIndex = 0;
for (var i = 0; i < words.length; i++) {
    var wordLength = words[i].length;
    var textRange = newTextFrame.textRange.characters[charIndex];
    textRange.length = wordLength;
    textRange.fillColor = colors[i];
    charIndex += wordLength;
}

How to fix it?

This topic has been closed for replies.
Correct answer renél80416020

Salut!

Je verrais plutôt cela:

 

 

 

// JavaScript Document
var doc = app.activeDocument;
var textRef = doc.textFrames[0]; // assume text frame is present

    for (var i = 0; i < textRef.textRanges.length; i++) {
       var Char = textRef.textRanges[i];   //alert(Char.contents)
       if (Char.contents == " ") {
         textRef.textRanges[i].remove();
         i--;
       }
    }

 

 

 

René

 

 

1 reply

renél80416020
renél80416020Correct answer
Inspiring
October 4, 2024

Salut!

Je verrais plutôt cela:

 

 

 

// JavaScript Document
var doc = app.activeDocument;
var textRef = doc.textFrames[0]; // assume text frame is present

    for (var i = 0; i < textRef.textRanges.length; i++) {
       var Char = textRef.textRanges[i];   //alert(Char.contents)
       if (Char.contents == " ") {
         textRef.textRanges[i].remove();
         i--;
       }
    }

 

 

 

René

 

 

Inspiring
October 4, 2024
great, thanks for participating