Tips for creating a line break in extendscript for Adobe Indesign

I am currently using extendscript to generate invoices based on downloaded plain text emails (.txt).

Within the text file, there are specific lines containing "Order Number: 123456" followed by a line break. I have a script that I've created using code snippets found on this platform which helps identify the end of "Order Number:" to determine the starting point of a substring. My goal is to use the position of the line break as the second index to complete the substring. To achieve this, I have incorporated another script from the knowledgeable members of this community to create an array of indexes for each occurrence of a character. I plan to select the array object with a higher value than the initial number for the substring.

It may seem complex, but my knowledge of Javascript is still developing, and I'm unaware of any simpler approach.

Is there a specific character I should use to simulate a line break in a txt file using Javascript for extendscript in InDesign?

Thank you.

I have attempted to use characters like \n, \r\n, and ^p, both with and without quotation marks, but they do not appear in the array upon testing.

//Load Email as String

var b = new File("~/Desktop/Test/email.txt");

b.open('r');

var str = "";

while (!b.eof)

    str += b.readln();

b.close();

var orderNumberLocation = str.search("Order Number: ") + 14;


var orderNumber = str.substring(orderNumberLocation, ARRAY NUMBER GOES HERE)

var loc = orderNumberLocation.lineNumber


function indexes(source, find) {
    var result = [];
    for (i = 0; i < source.length; ++i) {
        // If you want to search case insensitive use 
        // if (source.substring(i, i + find.length).toLowerCase() == find) {
        if (source.substring(i, i + find.length) == find) {
            result.push(i);
        }
    }
    alert(result)
}

indexes(str, NEW PARAGRAPH CHARACTER GOES HERE)

I aim to have all line breaks as an array of indexes stored in the variable "result".

Edit: The method I initially used to import the text file resulted in the removal of all line breaks. Implementing the code below instead has proved to be more effective. Now \n is functional.

var file = File("~/Desktop/Test/email.txt",  "utf-8");  
file.open("r");  

var str = file.read();  

file.close();  

Answer №1

If you want to extract specific fields from a string, you'll need to utilize Regular Expressions. The regular expressions can be adjusted based on the fields you are targeting. Here's an example to get you started:

var str; //your string
var fields = {}
var lookFor = /(Order Number:|Address:).*?\n/g;

str.replace(lookFor, function(match){
    var order = match.split(':'); 
    var field = order[0].replace(/\s/g, '');//remove all spaces
    var value = order[1];
    fields[field]= value;
})

In this code snippet, (Order Number:|Address:) is used to identify the fields you want to extract. You can include more fields separated by the "or" character | inside the parentheses. The .*?\n portion matches any character until the first line break. The g flag is used to find all matches in the string. By using str.replace, you can process each match individually. If the field and value are separated by a colon ':', the code splits the match into an array and stores the extracted values in an object. When executed, the code will produce the following object:

fields = {
    OrderNumber: 12345,
    Address: "my fake address 000"
}

Answer №2

Experiment with the use of \n and \r

For instance: indexes(str, "\r");

Answer №3

It seems like the solution you're seeking involves utilizing the str.split() method:

function findIndexes(source, find) {
    var order;
    var result = [];
    var orders = source.split('\n'); // This returns an array of strings: ["order: 12345", "order:54321", ...]
    for (var i = 0, l = orders.length; i < l; i++)
    {
        order = orders[i];
        if (order.match(/find/) != null){
            result.push(i)
        }
    }
    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

What purpose does generating a JSON file serve when invoking getStaticProps in Next.js?

Just diving into the world of Next.js. I've been going through the Next.js documentation and stumbled upon this: Next.js creates a JSON file that contains the outcome of executing getStaticProps. This JSON file is used in client-side routing via nex ...

What is the best way to retrieve all Objects by a specific property in React when working with an array of Objects?

I am looking to create a multiple checkbox filter where selecting the 'Accessories' option will display items with the 'Accessories' value under the 'type' property. However, before I proceed with that, I need to ensure that I ...

Can local storage be accessed within a function and utilized during the Windows.onload event?

I have an onclick function that dynamically returns 'x' and stores it in a div. However, after a page refresh, the dynamic div resets and the data is lost. To prevent this, I stored the data in local storage within the 'test' function a ...

Ajax request not populating controller with data in ASP.NET CORE MVC

`Hello everyone, I'm running into a problem with my colleague's assignment and could really use some assistance. The issue pertains to ASP.NET Core MVC. I have an API Controller for editing student groups. This API Controller receives a GroupView ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

Import a JSON file into Parse by reading and parsing it to store in the database

I am currently facing a challenge with parsing JSON data in my Parse Cloud function. After fetching the JSON file, I need to parse the data and populate one of my classes with the results. However, I'm having trouble figuring out how to properly parse ...

Experiencing delays with AngularJS $http responses

I have this code snippet which is causing an issue: $http.get('/api/users'). success(function(data) { $scope.authors = data; }). error(function() { console.log('API error - configuration.') }); Further down in the code: for ( ...

Tips for concealing a div when the inner HTML contains a particular string

Here is the current content I am working with: <div class="showcaseBeds">0 Bedroom</div> <div class="showcaseBaths">0.00 Total Bathroom</div> <div class="IDX-showcaseBeds">3 Bedrooms</div> <div class="IDX-showcas ...

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

The system is facing difficulty in accessing the property 'user_first_name' as it is currently undefined

I'm having trouble registering a user with expressjs/mongoose as I keep receiving the error: TypeError: Cannot read property 'user_first_name' of undefined at C:\Quiz webPolitica\server.js:20:24 at Layer.handle [as handle_request] ...

Trigger jQuery when a breakpoint has been met

I am working on a responsive design that has multiple breakpoints. Within the content, some block dimensions are calculated using jQuery. Whenever the viewport changes, these dimensions also change and therefore the calculation needs to be re-run. How can ...

Leveraging Javascript/Jquery for numbering items in a list

This is a snippet of HTML code that I am working with: <ul> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data ...

The MPI_Gatherv function is causing the root's array to receive garbage values

I have been working on incorporating the MPI_Gatherv function into my C code. In my implementation, each process, including the root, is supposed to create a local array with a size equal to its rank plus one. The elements in this array should represent t ...

Methods to modify the state of a Modal component beyond the boundaries of a React class

I am attempting to trigger my modal by modifying the state from outside of the react class. Unfortunately, I have had no success thus far. I have experimented with the following approach: In my code, I have a method named "Portfolio" that is responsible f ...

Initial Search Function in a MEAN Stack Site

Working on a MEAN stack application for a school project, I'm almost done but struggling to add search functionality. Creating a search feature for ICD-10 codes in a medical app is my goal. Just need a basic search of symptoms or codes that displays ...