MacMost Q&A Forum • View All Forum QuestionsAsk a Question

How Do I Access Pages Document Content With Javascript?

Hi! I really would like to access the text body of a pages document and count the occurrences of a certain word in it with javascript.

I would guess it is something like

var Pages = Application(“Pages”);
pagesdoc =‘path to document’));
var text = pagesdoc.body
var count = (text.match(/certain word/g) || []).length;

Would be really great if you could help!


Comments: 3 Responses to “How Do I Access Pages Document Content With Javascript?”

    2 years ago

    You don’t need to use JavaScript for that at all. Just do a search. In Pages, choose Edit, Find, Find (Command+f) and then search for the word. Then you’ll see the number of results right there in the search box in gray, toward the right. Like “12 found.”

    André Kerber
    2 years ago

    Thank you very much for the fast answer. My goal is to have a javascript which searches a lot of pages documents for certain words and populates a table with the counts. So which whould be the command in javascript put the text body of a pages document into a string?

    2 years ago

    Ah, you didn’t mention that you wanted more than just to do it a single time. You can find full documentation for JXA/JavaScript and how it works with Pages in the ScriptEditor app library. If you will be tackling this task, I would look through that.
    You use bodyText() to get the text inside a document in the body of a word processing document. Like this:
    var app = Application(“Pages”);
    app.includeStandardAdditions = true;
    var doc = app.document;
    var text = doc.bodyText();

Comments Closed.