How can I efficiently extract neighboring characters from a JavaScript array of strings?

Imagine this scenario:

We have an array like this: var arr = [ "Exploring the zoo, we saw every kangaroo jump and quite a few carried babies.", "The wizard quickly jinxed the gnomes before they vaporized.", "The quick brown fox jumps over the lazy dog."];

I am currently working on a way to extract characters surrounding a specific input in the array. For example, if I enter "jinxed", I want to retrieve "wizard quickly" and "gnomes before". It doesn't have to be entire words, just a few characters around the input. I've been struggling with this problem, so any suggestions or tips would be greatly appreciated.

Thank you!

Answer №1

function searchArrayForWord(array, term) {

    // This function aims to help find a specific word within an array.
    // It looks for the first occurrence of the word but may not cover all cases or be optimized.
    // Further specifications can make it more versatile.
    // Hopefully, this code snippet provides some assistance.

    var 
        // utilities
        regWord = /\w+/g,
        wordsBefore, wordsAfter,
        matchedWord,
        found = false;

    // loop through the given array
    array.forEach(function(item) {

    if (found) {
      // skip iteration if the word is already found
      return false;
    }

    // clear arrays for words before and after the target word
    wordsBefore = []; 
    wordsAfter = [];

    // extract words from the current array item
    while (match = regWord.exec(item)) {

      // get the matched word 
      matchedWord = match[0].toLowerCase();

      // check if the desired word is found
      if (matchedWord === term.toLowerCase()) {

        // mark as found
        found = true;

      } else {
        // handle words that appear before or after the target word

        if (!found) {
          // populate the array of words before
          wordsBefore.push(matchedWord);

        } else {
          // populate the array of words after the target word
          wordsAfter.push(matchedWord);

        }

      }

    }

  });

  // return an object with words before and after the target word
  return {
    wordsBefore: wordsBefore,
    wordsAfter: wordsAfter 
  } 

}

Answer №2

To retrieve the text before and after the term jinxed, you can utilize the function split. From there, you can use substr to extract either the first or last characters of each section:

let sentence = "The mystical cat jinxed the cursed mouse with a spell";
let parts = sentence.split('jinxed');

parts == [ 'The mystical cat ', ' the cursed mouse with a spell' ]

parts[0].substr(-8) == 'stical cat '
parts[1].substr(0,10) == ' the cursed'

Answer №3

If you're looking to search for specific characters within a string, you can utilize RegEx match function:

function search(s,q, msg) {
  // utilize RegEx to match the characters before and after the query
  var matched = s.match(new RegExp("(.|^)" + q + "(.|$)"));
console.log(matched);
  // if there was a match found, remove the 1st element (which is the entire matched pattern)
  if (matched) {
    if(matched.length>1) {matched = matched.splice(1)}
    // matched[0] represents the character before, matched[1] represents the character after
    alert(msg + " '" + matched[0] + "', '" + matched[1] + "'");
  } else {
    alert(msg + " not found");
  }
}

search("The wizard quickly jinxed the gnomes before they vaporized.","jinxed", "in the middle");
search("jinxed the gnomes before they vaporized.","jinxed", "in the beginning");
search("The wizard quickly jinxed","jinxed","in the end");
search("jinxed","jinxed","full");
search("The wizard quickly","jinxed","not in string");

It's worth noting that this method also applies when the target string is located at the beginning or end of the line.

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

The debounce function seems to be malfunctioning as I attempt to refine search results by typing in the input field

Currently, I am attempting to implement a filter for my search results using debounce lodash. Although the filtering functionality is working, the debounce feature seems to be malfunctioning. Whenever I input text into the search bar, an API call is trigge ...

Express functions properly when handling the root route, but encounters issues with sub routes as it sends empty response bodies

Inside the routes.ts file: const router:Router = express.Router() // Route to get all blogs router.get('/',async (req:Request,res:Response)=>{ res.status(200).send("message sent") }) router.get('/admin',async (req:Requ ...

What is causing me to be unable to concentrate on specific elements when utilizing react refs?

I encountered a strange scenario where I had a collection of references to various form elements like buttons, different types of inputs, and more. I then generated an error summary that, when clicked, automatically focused on the element in question, scro ...

Executing JavaScript functions from an ASP.NET Razor view is achieved by using the

While working on a view in which I am writing Razor code, I encountered the need to call a JavaScript function with the JSON generated by the Razor code: // JavaScript function function buildTemplate(currentTemplate) { alert('hello world'); } ...

Using AJAX and Spring MVC to render JSON objects in bracket notation within a POST request

Why is a JSON rendered in bracket notation when bound to a Web Request? I am working on an application that involves making 2 consecutive REST Controller calls. The first call reads an address from a form, serializes it, sends it via AJAX to a validation ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Tips for reading a two-dimensional triangle array from a text file

I am trying to extract a 2D triangle array from a text file. 1 8 4 2 6 9 8 5 9 6 After writing this code, I attempted to print out the array to verify if it was accurate. However, despite successful debug prints, the array does not print when running the ...

Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button ...

An issue arises when attempting to integrate ajax with colorbox

I am currently facing an issue with a WordPress plugin designed for playing videos. It seems that the developer who created it is no longer available, and now the play video button has stopped working. Upon further investigation using Firebug, I noticed ...

Using jQuery, for every button click within a specific class, the content of a div stored in variables should be replaced based on the attribute value

I have a few buttons inside a div. The challenge is to display different content depending on the value attached to the "link" attribute after clicking. When a button is clicked, a function retrieves the value inside the "link" attribute and if it matches ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

Tips for storing and recalling a 24-hour countdown timer using Local Storage

I'm new to JavaScript and I have a 24-hour countdown timer that resets on page reload. However, I want to use LocalStorage to save the starting progress so that it continues running even if the page is closed or refreshed. The goal is for the timer to ...

Calculate the total from performing vlookups on various columns

I am attempting to minimize redundancy by using the following formula: =IFERROR(VLOOKUP($C3,'Business Goals'!$A$3:$C$8,3),0)+ IFERROR(VLOOKUP($D3,'Business Goals'!$A$3:$C$8,3),0)+ IFERROR(VLOOKUP($E3,'Business Goals'!$A$3:$C$ ...

Maintaining personalized variable values for individual connected clients in Node.js: What's the best approach?

I have recently started working with Node.js and I am using Visual Studio 2015 with the Basic Node.js Express 4 app template. After setting some values through a post request from the client, I noticed that when I open another tab and send another post re ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

Nodemon may have failed to install correctly

When trying to install nodemon globally, I encountered an error. How can I resolve this issue? C:\Users\nipuna\Desktop\nodejs>npm install -g nodemon npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules\ ...

There are various reasons why React components do not utilize explicitly defined styles

I've encountered a puzzling issue while working on a React component that includes other components. Despite specifying styles in the parent component for its children, the specified styles are not being applied. Strangely enough, when I enclose the c ...

Unusual Encounters in Laravel: Navigating with React Router and the Back Button

I have nearly completed building a weather application with Laravel and have decided to integrate the front end using React/Redux/React-Router while utilizing Laravel for API calls. The only aspect that I have chosen to keep unchanged is my customized Lara ...

Mastering JSON looping for each distinct group

I'm new to JavaScript and recently encountered an issue with JSON. Here is the object I am working with: var users = [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName": ...

The Instagram API seems to be experiencing some technical difficulties

My expertise lies primarily in HTML/CSS, with limited knowledge of using APIs and JavaScript. I have been assigned the task of utilizing an API to retrieve Instagram pictures posted by users with a specific hashtag. Here is the demo shared via JSFiddle: ...