Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so:

var getSelectedText = function() {
  var text = "";
  if (typeof window.getSelection !== "undefined") {
    text = window.getSelection().toString();
  } else if (typeof document.selection !== "undefined" && document.selection.type === "Text") {
    text = document.selection.createRange().text;
  }
  $scope.annotations = annotationList();
  return text;
};

This selected string is extracted from the following longer text:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book... etc

Now, my goal is to determine the start and end offsets of this selected text within the larger string.

but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised

Any suggestions on how to achieve this using JavaScript?

Answer №1

Try this out and take a look at the comments:

var text = 'this is a sample text where we will search for a specific phrase';

function findPhrase(text, phraseToFind){
  var position = text.indexOf(phraseToFind);
  if(position !== -1){
    // If the phrase is found within the text
    // Start offset will be the position of the phrase
    // End offset will be the total length of the text minus the length from start to end of the phrase

    var endOfPhrase = position + phraseToFind.length;
    var endOffset = text.length - endOfPhrase;
    return { startOffset: position, endOffset:  endOffset}
  } else {
     return 'Phrase not found in the text!'
  }
}

findPhrase(text, 'search for a specific phrase')

Answer №2

To retrieve the starting and ending positions of a selected text within a node, you can utilize the Selection object provided by the getSelection method.

You can see a demonstration here.

document.onselectionchange = function() {
  console.log('New selection made');
  let selection = document.getSelection();
  console.log(selection);
  console.log(selection.anchorOffset);
  console.log(selection.focusOffset);
};

It's important to note that the anchor offset and focus offset do not directly correspond to the start and end indexes of the selection. In cases where the user selects text from right to left, the anchor offset will exceed the focus offset.

Consider the enumeration of both offsets based on your specific requirements.

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

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

Differences Between Angular Routes and $resourceComparing Angular

In my application, I have a set of REST URLs that I need to fetch and display as HTML content upon user request. When the user searches for a first name and it is found, the HTML is populated from JSON data retrieved from the initial URL. Initial URL va ...

jQuery image resizing for elements

I have successfully adjusted the images in the gallery to display one per row for horizontal orientation and two per row for vertical orientation. Now, I am facing a challenge in making the images scalable so they can resize dynamically with the window. A ...

AngularJS is known for its ability to handle invalid HTML inserts

I am currently working on an app that relies on piecing together HTML from various APIs. Although we have attempted to move away from this approach multiple times, it always seems like the best solution in the end. While it may work well for now, I hope to ...

Stop unnecessary re-rendering of controlled React inputs

Recently, I delved into the world of React.js and came across controlled inputs. Sample Code: Check out my simple implementation: import React, { useState } from 'react'; const MyForm = () => { console.log('rendered'); // Li ...

Ways to position divs without causing them to collapse or override existing divs

I am currently developing a demonstration in which users can select jQuery areas to create square blocks. When a user selects an area and adds a comment with color, the entire block is displayed at a specific position. This feature is working perfectly as ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Is it possible to determine the search query if the search term appears within the website URL?

I'm trying to figure out which action url and name term to use when the search term is located in the middle of the URL. For instance, the HTML code below enables me to type text and upon pressing enter or the button, it redirects me to the website w ...

Arrange a JSON array by searching texts initially, followed by sorting the remaining results in alphabetical order

I am looking to sort a JSON array in JavaScript based on a search text. The sorting should prioritize items that match the search text at the beginning of their value, followed by alphabetical sorting for the remaining results. Even if the search text is f ...

My navbar in bootstrap is having trouble staying aligned with the button and search box. What can I do to ensure everything stays in line?

<nav id="NavbarMaster" class="navbar NavCompression"> <!-- style="min-height:100px;" --> <div id="navToggler" class="container-fluid TitleBG TitleHeight"> <div id="navopener" class="Pointer" style="position:fixed;top:0;left:0; ...

Determining Visibility of DIV ID using JQuery

Can anyone help me determine if a DIV element is hidden or visible using jQuery? Here is the pseudocode I have so far: if(DIV != VISIBLE) // not visible { show content } Any jQuery experts out there who can lend a hand? Thank you, Robert ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

Ways to conceal a child div element without using any specific ID reference

I encountered an issue where I need to conceal all divs within a parent div except the first one. The challenge is that these divs do not possess any unique identifiers. Is there a way to achieve this task using CSS or pure JavaScript? <div role="list ...

Material UI Table dynamically updates with Firestore real-time data

My current code aims to update a Material UI table in real-time with data from a Firestore database. I can fetch the data and store it in an array, but when I assign this array to the table data, nothing changes. I've heard that I should use states fo ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

The AJAX request is functioning properly, however, when I attempt to click the icon within the button, a 500 internal server error is triggered

Encountering a 500 internal server error specifically when attempting to click the thumbs-up icon within the like button: <button class="submit-btn like" id='{{ $image->id }}'> <i class="far fa-thumbs-up"></i> Like </ ...

Is there a way to add a price to an object in JavaScript?

Purchasedata.find(function(err, purchasedatas) { if (err) { return handleError(res, err); } var totalprice = 0; for (var i = 0; i < purchasedatas.length; i++) { findProduct(i, function(i, price) { }); } ...

What are the risks of using react + bootstrap without importing bootstrap.js?

When bootstrap library is used along with React, potential unpredictable behavior and difficult bugs may arise due to DOM modifications. Is it feasible to use bootstrap without including bootstrap.js? What are the drawbacks? While I am aware of the ' ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...