Locating the Index of a Line Break Starting from a Specified Position in JavaScript

Stored in my variable description is the following text:

`This is a code update`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 


**SCTOMJ**

I am looking to extract the data associated with the phrase

Official Name', specifically '2011 New York City Electrical Code
. To do this, I initially used the code snippet below:

var official_name = description.search("Official Name:"); 
if(official_name != -1){
    official_name = description.substring(official_name + 14, description.indexOf("Code Tile Name:")).trim();
}

The issue with the current code is that it relies on the fixed location of the phrase "Code Tile Name:", which is not ideal as the structure of the information may vary. I am seeking a solution that is not dependent on specific sequence.

Is there a method to locate the first newline character after a given position?

Thank you!

Answer №1

Employ a look behind assertion to locate the line that initiates with "Official Name:". The string after the official name should encompass all characters excluding line breaks.

Note: utilize the multiline flag (/m) to ensure that the expression ^Official Name seeks the beginning of lines, not the entire text's start.

const str = `\`This is a code update\`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 


**SCTOMJ**`

const result = str.match(/(?<=^Official Name:)[^\n\r]+/m)

console.log(result?.[0].trim())

Answer №2

Another option is to utilize a capture group:

^Official Name:[ \t]*(.+)

Clarification

  • ^ Indicates the start of the string
  • Official Name: Matches this literal phrase
  • [ \t]* Matches any optional spaces or tabs
  • (.+) Capture group 1, matching one or more characters excluding newlines

View Regex demonstration here

const s = `\`This is an update on the code\`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 


**SCTOMJ**`

const m = s.match(/^Official Name:[ \t]*(.+)/m)
if (m)
  console.log(m[1]);

Answer №3

A solution is available.

The indexOf function requires two parameters, the first being the character to look for and the second indicating where to start the search.

indexOf(character_to_search, index_to_start_search)

Quick tip- Instead of manually entering 14 in your code, you can dynamically determine the length of the word "Official Name."

Check out this example-

const description = `\`This is a code update\`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 


**SCTOMJ**`

var c = "Official Name:"
var official_name = description.search(c); 
if(official_name != -1){
    official_name = description.substring(official_name + c.length, description.indexOf("\n", official_name)).trim();
}
console.log(official_name)

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

Problems persist with storing Node.js values in database

I need help inserting values from a socket emit into my database. Here is the code I am using: socket.on("chat message", (data) => { var sql = "INSERT INTO tbl_user_chats (sender,receiver,message,created_at,ad_id,category_id) VALU ...

Guide on designing a form for generating custom URLs

I have a form on my website that generates a URL, but it requires the user to wait until the entire page is loaded in order to function properly. I believe this is because I am using window.onload and should switch to using $(document).ready instead. How ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

The issue of v-bind:checked not functioning properly across all component instances

Presenting a unique radio list component: <template> <div class="list"> <div class="radio"> <input type="radio" name="custom-radio-list" :id="'custom-radio-full-' + cid" value="" @change="updateCustomRadio" ...

Is it possible to use asp:LinkButton in ASP.NET without relying on Javascript?

I'm interested in utilizing an asp:LinkButton, as it resembles a link while also having a server-side Click handler. However, the web-server appears to have difficulty detecting if JavaScript is disabled on the client side, resulting in rendering iss ...

The TouchBarButton function cannot be used as a constructor

Encountered an error while using Electron: This is my code for a Better Discord add-on written in JavaScript. I am relatively new to JS, so any assistance would be greatly appreciated. Thank you. //META{"name":"BetterTouchbar"}*// cons ...

Developing an intricate nesting structure for an object

this is my code snippet: "book" => {b:{o:{o:k:{'end':true} could someone please provide an explanation or a helpful link for this? const ENDS_HERE = '__ENDS_HERE' class Trie { constructor() { this.node = {}; } insert(w ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

Modify css backgroundPosition with Jquery dynamically for both left and top offsets

As a beginner programmer and not a native English speaker, I apologize in advance for any coding or language errors. My goal is to create a 'cropping effect' by making a table draggable over an image. When the table is dragged, I want to replace ...

managing the focus and blur events within an Angular 1.5 component

While working on an angular js project recently, I encountered a situation involving handling focus and blur events in a textbox. My specific scenario required adding the $ sign when focus is lost from the textbox and removing it when the textbox is focuse ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

Is there a way to consistently keep the cursor in a single form field using HTML5 and Javascript?

My goal is to ensure that the focus remains on a specific form field at all times. I want this field to be the active one so that any text input goes directly into it. How can I achieve this? I have already tried using the HTML5 autofocus command, but once ...

Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial app ...

Learn the process of connecting checkboxes to a database in MeanStack using Angular

Hey everyone, I'm currently working with AngularJS ng-repeat and I am trying to dynamically bind a checkbox based on a true or false value from the database. However, even when the database value is set to true, the checkbox does not automatically che ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

Unable to fetch JSON file from the local server

I'm trying to develop a server API using Koa. This server will have a single API endpoint, /api/data, which should read a local json file and display its content in the browser when a user accesses localhost:3000/api/data. const Koa = require('k ...

Ensure the security of Node.js runtime by either enabling protection measures or turning off debugging

I currently have a nodejs application that utilizes Javascript to interact with online services by reading stdin for username and password input. Throughout the 24/7 running of the application, these credentials are stored in variables for potential re-lo ...

Step-by-step tutorial on designing an input slider to dynamically adjust the CSS :before linear-gradient values

Is there a way to achieve a gradient effect using pseudo-element :before on an image that can be customized by adjusting a slider input? I've been trying to implement this feature with the following code, but have not been successful so far. var ...

What are some ways to enhance Javascript performance using Closure Compiler while preserving function names?

Seeking a solution for using specific functions from a Javascript file (lib.js) in a webpage without loading the entire file. I am looking to achieve this through command line scripting, but have not yet found a method that works as desired. The content ...