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

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

Guide on extracting unique identifiers from an array of objects and sorting them by the earliest date in JavaScript

I've got an array of objects and I'm looking to retrieve the items with unique IDs while also selecting the earliest date. For example: [{id:1, date: Jan 12}, {id:2, date: Feb 8}, {id:3, date: Feb 8}] var array = [{id: 1, date: Jan 12 2021 08:00 ...

What is the process for integrating ion-tabs with IonicVueRouter within an Ionic (vue.js) application?

My Project Idea I have a vision to create an innovative exercise warm-up application. The app will be divided into two main sections: a workout tab and a settings tab. The user journey will start with selecting a workout plan, then choosing specific exerc ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

Using a button click to toggle the vue-ctk-date-time-picker in VueJS

Currently, I am utilizing the Vue component - https://github.com/chronotruck/vue-ctk-date-time-picker within my own component. However, I am encountering an issue where I would like to maintain the component's original functionality while having a but ...

Use jQuery to drag an element and display controls in a designated area

I am trying to develop a tool that allows me to drag an image from one section to another, and upon dropping it, the following actions should take place: 1 - The dragged image should revert back to its original position 2 - A set of controls should be add ...

Yup will throw an error if both a minimum value is set and the field is also marked

I am attempting to validate my schema using yup: import * as yup from "yup"; let schema = yup.object().shape({ name: yup.string().min(5) }); const x = { name: "" }; // Check validity schema .validate(x, { abortEarly: false }) . ...

The function Document.getElementsByName() behaves differently in Internet Explorer, returning an object, compared to Chrome where it returns

While trying to meet my requirements, I encountered a discrepancy between running the page in IE browser versus Chrome. The code worked successfully in IE, but not in Chrome. for(var gridNo=0;gridNo < 30;gridNo++){ var fldId = arry[0]+'_& ...

JavaScript: Changing the names of all object keys

As a beginner, I am struggling to rename some objects in my key using a map function. Below is my current array: "platforms": [ { "id": 6, "name": "PC (Microsoft Windows)" }, { "id": 11, "na ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

I can't figure out why I keep getting the error message saying that $ is not

Looking to execute a PHP file using AJAX, I attempted the following: <html> <script type="text/javascript"> setInterval(function(){ test(); },3000); function test(){ $.ajax({ type: "POST", url: "GetMachineDetail.php", data: ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Add small pieces of content to CKEditor

Is there a way to add "atomic" block content into CKEditor? For instance, I would like to add <h1>Test</h1> right after the letter "B" in the sentence <p>A B C</p>. Currently, when using CKEDITOR.currentInstance.insertHtml('&l ...

What could be causing the jQuery .load() function to trigger twice?

While using jQuery 1.4 along with jQuery History, I noticed that Firebug/Web Inspector are displaying 2 XHR GET requests on each page load (which doubles when visiting the homepage (/ or /#). For example, if you visit this or any other page with Firebug e ...

Develop a JavaScript library for use in the npm ecosystem

I have developed a minimalist JavaScript library that includes common functions: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...