Tips for locating the index of a substring within a string with varying line endings using Typescript

I am faced with the task of comparing two strings together.

  1. abc\r\ndef
  2. c\nde

My goal is to determine the index of string 2 within string 1.

Using the indexOf() method is not an option due to different line endings, so I require an alternative solution that takes this into account.

It's important that I do not alter the original string as I need the substring index in reference to the original. Simply replacing all instances of \r\n with \n would disrupt the original indexes, necessitating a restoration process.

Answer №1

(For what it's worth, there's no need for TypeScript in this question. It's all about JavaScript.)

To achieve this, you can convert the target string into a regular expression by using the alternation \r\n|\r|\n wherever these sequences appear. Make sure to escape the parts in-between (refer to this question's answers for assistance). When you use the `exec` method of the resulting regex on the initial string, if it finds a match, the result (referred to as `match`) will contain the index at `match.index` and the matched text at `match[0]`.

Here is an example with TypeScript type annotations commented out:

// Adapted from https://stackoverflow.com/a/3561711/157247
function escapeRegex(string) {
    return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

function test(str/*: string */, substr/*: string*/) {
    // Break down the text based on newline sequences,
    // escape the parts in-between,
    // then combine them with an alternation
    const rexText = substr
        .split(/\r\n|\n|\r/)
        .map((part) => escapeRegex(part))
        .join("\\r\\n|\\n|\\r");
    // Create the regex
    const re = new RegExp(rexText);
    // Execute it
    const match = re.exec(str);
    if (match) {
        console.log(`Found ${JSON.stringify(match[0])} at index ${match.index} in ${JSON.stringify(str)}`);
    } else {
        console.log(`Not found`);
    }
}


test("abc\r\ndef", "c\nde");

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

I am encountering issues in Vue JS when using ternary expressions alongside v-if statements

Snippet:- <template> <div id="calendars-results"> <div class="vs-con-loading__container"> <div class="vs-row flex justify-between"> <h4 class="vs-row mb-2">{{ title } ...

Tips on storing the amount of time a user devotes to answering questions on my form into a database

I am facing an issue with storing the "duration" in my database. The "duration" I aim to store is the time spent by the user answering a question I created. When they click the submit button, I want to save the duration they spent in the database. Below i ...

Navigating URL to switch data access

Is there a way to toggle the visibility of a div when I add #ID at the end of the URL? For instance, if I access a URL like domain.com/xxxxxx#01, then the specified div should be displayed. $(document).ready(function() { $(".toogle_button_<?php echo ...

What is the most effective way to delete a single value from a key with multiple values stored in local storage?

This question has come up before, but the solutions provided didn't work for me, which is why I am asking it again. Currently, I am storing values in an array that is then stored in local storage. Here is the object: data.items - 0: {id: 190217270, ...

Vue.js component function "not instantiated within the object"

I recently started learning vue.js and decided to use vue-cli to set up a new project. As I was working on adding a method to a component, I encountered some issues: <template> <div> <div v-for="task in $state.settings.subtasks& ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

Guide to adding a checkbox to a JavaScript list

I'm currently working on building a task list using JavaScript. The concept is to type something into the input field and then, when the user clicks the button, a checkbox with that text will be generated. However, I'm facing an issue as I am no ...

Tips for enabling browser back and forward functionality in a one-page website design

Building on the previous discussion about optimizing a horizontal sliding layout (Most efficient way to do a horizontal sliding layout), I'm curious if it's feasible to enable the back and forward buttons in the browser when implementing a single ...

Django and VueJS: Error 403 - Forbidden request due to missing or incorrect CSRF token

My tech stack includes Django and Django REST framework on the backend, along with Vue.js on the frontend. While GET requests function smoothly and POST requests using Postman or Insomnia work fine, encountering an error in the Browser console when sending ...

Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box? I've searched, but I could only find instructions for placing an icon as the background of the input element. I ...

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

Getting the JavaScript file name within another JavaScript file - a simple guide

Imagine having an HTML file that references two external JavaScript files. One of these JavaScript files contains errors (likely compilation errors), while the other file includes an onerror method without any issues. When you open the HTML file in a brows ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

What is the best way to showcase an ajax response on an HTML webpage?

Apologies for the length of the code, but I'm looking to condense it while maintaining the same functionality. Is there an alternative approach or method that could achieve the same results? I receive data from PHP, which is then passed to JavaScript ...

Homepage divided in two sections akin to the Tumblr landing page

Have you ever visited www.tumblr.com and noticed the '30 reasons...' link on the registration page that slides up and reveals a second page? I've been trying to figure out how they achieve this cool effect. Most tutorials show how to scroll ...

Insert an ellipsis within the ngFor iteration

I'm currently working with a table in which the td elements are filled with data structured like this: <td style="width:15%"> <span *ngFor="let org of rowData.organization; last as isLast"> {{org?.name}} ...

Setting the height of Material-UI TreeView

Looking for advice on how to set a fixed height or dynamically adjust the height of a material-ui TreeView to fit the display? I'd like a scrollbar to appear when the TreeView content reaches a height of 100 pixels, for example, or fills 100% of the ...

typescript add an html element to an existing html document

I'm experimenting with creating a dynamic HTML element using TypeScript to display on a webpage. In my .ts file, my code looks like this: const displayContent = document.getElementById("display-content") as HTMLOutputElement; var displayVariable = " ...

Filtering controls within a table are not displayed in VueJS

I have been attempting to implement date filtering in my data table based on a demo I followed. Despite meeting the filter requirements, no results are being displayed which is perplexing. Below are the imports and data from the file containing the table: ...