What is the best method for excluding all text except the 100 characters preceding and following a specific string?

Trying to filter a dataset with multiple entries of around 5000 characters.

Looking for 100 characters before and after a specific keyword.

Tried using regex for search and replace, but only found functions for extracting one keyword at a time.

Sample Input:

abc123cde345fgh678ijk910keywordbc123cde345fgh678ijk910

Expected output with plus-minus 5 characters:

jk910keywordbc123

Answer №1

Find a string of 100 characters, followed by a specific keyword, and then another string of 100 characters:

const str = 'abc123cde345fgh678ijk910keywordbc123cde345fgh678ijk910';
const match = str.match(/.{5}keyword.{5}/);
console.log(match[0]);

If you need to generate the pattern dynamically, use this approach:

const str = 'abc123cde345fgh678ijk910keywordbc123cde345fgh678ijk910';
const keyword = 'keyword';
const pattern = new RegExp(`.{5}${keyword}.{5}`);
const match = str.match(pattern);
console.log(match[0]);

If your pattern includes special characters like $, remember to escape them before using new RegExp:

// https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

const str = 'abc123cde345fgh678ijk910keyw$ordbc123cde345fgh678ijk910';
const keyword = 'keyw$ord';
const pattern = new RegExp(`.{5}${escape(keyword)}.{5}`);
const match = str.match(pattern);
console.log(match[0]);

Answer №2

To tackle this issue, one approach is to utilize the String.indexOf() method to locate the position of the desired keyword within the given input string, and then employ String.slice() to extract the characters within a specified range.

const str = 'abc123cde345fgh678ijk910keywordbc123cde345fgh678ijk910';

const getKeyword = (str, keyword, radius) =>
{
    let idx = str.indexOf(keyword);
    return str.slice(idx - radius, idx + keyword.length + radius);
}

console.log(getKeyword(str, "keyword", 5));
console.log(getKeyword(str, "keyword", 15));
console.log(getKeyword(str, "keyword", 1000));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

It's important to note that this method will still produce accurate results even if the specified radius exceeds the maximum length possible, as it will simply return the entire string in such scenarios.

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

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Which modal popup option is best: ASP.NET AjaxControlToolkit, jQuery plugin, or Greybox?

In my ASP.NET web forms application, I am in need of a modal popup that can present users with a preview of images based on their search criteria. For example, if they search for "dog," the popup should display all dog-related pictures. The search results ...

Node.js is throwing a JSON parsing error due to an unexpected end of input

Currently, I am attempting to analyze the JSON data that is returned using the following PHP code snippet; $UserData = $con->query("SELECT * FROM Discord WHERE RobloxID=".$UserId) or trigger_error($mysqli->error); $result = $UserData->fetch_a ...

"Enhance User Interaction with a Bootstrap Popup when Submitting Form Data via

As a junior web master, I have a simple question to ask. I have created a single page application for a client with a contact form at the end of the page. The validation is done using Bootstrap, but the only method I know to send the form data to a mail id ...

Chained module incorporating a specialized Angular form validation directive

I've been working on incorporating an angular form validation "plugin," but I've hit a roadblock trying to utilize the directive in a child module. As a test, I'm using the HighlightDirective example. @Directive({ selector: '[highligh ...

Making Ajax requests to a servlet from a JSP form and dynamically updating a <div> element with the response

As I navigate my way through learning about ajax, I am currently exploring how to execute an ajax call from a JSP form and then showcase the result in a designated div. The following JSP form effectively loads data into divOrderResultContainer; however, I ...

Limitations of jQuery: onClick function not transferable

I am struggling to achieve the following functionality for my navbar dropdown menus: When the screen size is greater than 992px, I want the navbar dropdowns to open on mouse enter. For screens smaller than 992px, I want the dropdowns to open on ...

Unlock the power of React Native by learning how to implement multiple routes within your

//Prev.jsx const handleClick = (row) =>{ const orderNumber = row.orderNumber.replace(/\D/g, '') console.log(orderNumber) navigate("/drivers/" + (driverId) + "/" + (orderNumber)) } //App.js <BrowserRouter& ...

Complex search queries in Mongodb using Mongoose

Is there a way to create a dynamic search bar that provides suggestions based on user input? For example, as a user types "j", they see options like "Java, JavaScript, JQuery", and when they add "a", they only see "Java, JavaScript". Here is the structure ...

Retrieve child and descendant nodes with Fancytree JQuery

I'm currently utilizing Fancytree and have created the following tree structure: root |_ child1 |_ subchild1 |_ subchild2 |_ subchild3 |_ subchild4 When the selected node is child1, I am able to retrieve the fir ...

Navigating the route with quickness

Upon accessing the localhost, I encountered an issue with the code snippet below: When I try to access it, I receive an error message saying "Cannot GET /". var express = require('express'); var router = express.Router(); /* GET home page. */ r ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

When making an API request, the response includes the body of the data, however, the specific properties cannot be

I've encountered an unusual bug while using the Mapbox geocoding API. const geocode = async (address, callback) => { const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=token&limit=1` try { ...

Once the project is already created, you can integrate SASS into Angular CLI

Currently, I'm working on an Angular 4 project that was built using the Angular CLI. I'm aware that you can specify SASS as the styling option when creating a project with the Angular CLI, like this: ng new ProjectName --style=sass Now, I&apos ...

Passing references using a personalized component

So, I've encountered this issue with my code: import MuiDialog from "@mui/material/Dialog"; import { styled } from "@mui/material/styles"; const TheDialog = styled((DialogProps) => ( <MuiDialog {...DialogProps} /> ))(( ...

What is the proper way to utilize JQuery and Ajax to communicate with a global function in writing?

My goal is to retrieve data from an AJAX request and store it in a global variable. Despite trying to make the call synchronous, I am encountering issues where the value of the global variable becomes undefined outside of the Ajax request. I have attempt ...

Vue - Issue with reading properties of undefined while dropping a file

Trying to drag and drop an mp3 file into a dropbox on my website is proving challenging. Each time I test it, no matter the file I drop, the same error persists: Uncaught TypeError: Cannot read properties of undefined (reading 'files') Below is ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

Looking for a specific portion of a key-value pair

Currently, I am working on developing an application that will showcase parking tickets issued in New York City. The API that I am utilizing can be found at this link. My goal is to generate a graph illustrating the number of tickets handed out per month. ...

The `col-md-4` element from Bootstrap 4 is not functioning properly within my ejs file

<div class="container"> <div class="row card-deck"> <% for(var i=0;i<campgrounds.length;i++){ %> <div class="card col-12 col-md-4"> <img class="card-image-top" src="<%= campgrounds[i].image %>" ...