Determine if the given text includes a specific sequence of characters, without the need for them to be directly

I am developing a custom function that determines whether a specific sequence is present within a given text. Unlike traditional methods that check for substring inclusion, this function does not require the characters to be adjacent. For instance, in the string "Lord Of The Rings," the substrings "LOTR" or "other" should return true as they can be found within the string.

function checkSequence(text, sequence) {
    if (text.indexOf(sequence) !== -1){
        return true;
    }
    return false;
}

console.log(checkSequence("lord of the rings", "")); // True
console.log(checkSequence("lord of the rings", "lord")); // True
console.log(checkSequence("lord of the rings", "lens")); // True
console.log(checkSequence("lord of the rings", "other")); // True
console.log(checkSequence("lord of the rings", "l o t r")); // True
console.log(checkSequence("lord of the rings", "Lord")); // False
console.log(checkSequence("lord of the rings", "orks")); // False
console.log(checkSequence("lord of the rings", "z")); // False

However, the typical approach using indexOf() method might give incorrect results when checking for "LOTR" or "something." The code snippet provided showcases some examples I am currently testing with.

Thank you!

Answer №1

Uninteresting (Yet Efficient) For-Loop Approach:

Revamped to end the loop immediately once the outcome is determined; like when there are more characters left in the sequence than in the text.

function contains(text, sequence) {
  for (var i = 0, j = 0; i < text.length && j < sequence.length; i++) {
    if (text.length - i < sequence.length - j) return false
    if (text[i] === sequence[j]) j++
  }
  return j === sequence.length
}


console.log(contains("lord of the rings", "")); // True
console.log(contains("lord of the rings", "lord")); // True
console.log(contains("lord of the rings", "lens")); // True
console.log(contains("lord of the rings", "other")); // True
console.log(contains("lord of the rings", "l o t r")); // True
console.log(contains("lord of the rings", "Lord")); // False
console.log(contains("lord of the rings", "orks")); // False
console.log(contains("lord of the rings", "z")); // False

Answer №2

To check if a text matches a specific sequence, you can convert the sequence into a regex pattern. Here's an example:

function checkMatch(text, sequence) {
  if(!sequence.length) return true;                       // returns true if sequence is empty
  
  var regex = new RegExp(sequence.split('').join('.*'));  // create the regex pattern

  return regex.test(text);                                // check if the text matches the regex pattern
}

console.log(checkMatch("lord of the rings", ""));
console.log(checkMatch("lord of the rings", "lord"));
console.log(checkMatch("lord of the rings", "lens"));
console.log(checkMatch("lord of the rings", "other"));
console.log(checkMatch("lord of the rings", "l o t r"));
console.log(checkMatch("lord of the rings", "Lord"));
console.log(checkMatch("lord of the rings", "orks"));
console.log(checkMatch("lord of the rings", "z"));

If the sequence is, for instance, 'txt', the generated regex would look like /t.*x.*t/. This regex will match the characters t, x, and t in that specific order with any number of characters (including none) in between.

Answer №3

To transform the ordered series, you can create a case-insensitive regex pattern like this:

/L.*O.*T.*R/i

...where .* represents zero or more occurrences of any character:

function checkForSequence(text, orderedSeries) {
  return (new RegExp(
            orderedSeries.split("")
                    .map( (character) => character.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') )
                    .join(".*"),
            "i")
         ).test(text)
}

console.log(checkForSequence("lord of the rings", "")); // True
console.log(checkForSequence("lord of the rings", "lord")); // True
console.log(checkForSequence("lord of the rings", "lens")); // True
console.log(checkForSequence("lord of the rings", "other")); // True
console.log(checkForSequence("lord of the rings", "l o t r")); // True
console.log(checkForSequence("lord of the rings", "Lord")); // True
console.log(checkForSequence("lord of the rings", "orks")); // False
console.log(checkForSequence("lord of the rings", "z")); // False
console.log(checkForSequence("Hi. How are you?", "i.?")); // True

The complicated

.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
section is used to escape special characters in the input that may have significance in regular expressions.

Answer №4

If the order of the sequence is not important, utilizing a Set can be beneficial. The time complexity for this approach is O(n+m), which corresponds to the combined lengths of the text and the sequence.

To implement this method, store the characters in the Set and then utilize set.has(value) for verification.

function validatePresence(text, sequence) {
  var characterSet = new Set();
  for (var i = 0; i < text.length; i++) {
      characterSet.add(text[i]);
  }
  for (var i = 0; i < sequence.length; i++) {
     if(!characterSet.has(sequence[i])) return false;
  }
  return true;
}

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

Using SCSS to apply a class in Next.js

Currently, I am working on a project using Next.js and implementing the SCSS module procedure for styling. An example component directory structure is as follows: SampleComponent -> index.tsx and SampleComponent.module.scss The code in SampleComponent ...

Creating directional light shadows in Three.JS: A Step-by-Step Guide

Can shadows be generated using a DirectionalLight? When I utilize SpotLight, shadows are visible. However, when I switch to DirectionalLight, the shadow functionality doesn't seem to work. ...

Creating a filter using radio input in HTML and CSS is a simple and

Currently, I am delving into the world of Javascript and React, but I have hit a roadblock. My goal is to create a Pokedex, yet I am encountering some difficulties. I have implemented Radio Inputs to filter Pokemon by generation, but I am struggling with ...

The MVC Controller is unable to retrieve decimal values from an Ajax POST request

I am facing an issue with the POST function in my code. While string and integer values are reaching the Controller without any problem, double values are not being received on the server side. Interestingly, when I test on my local machine, everything wor ...

Invoke the parent function when extending javascript prototype

Below is the Meta-Code I am currently working with: var Parent = function(){} Parent.prototype.doSomething = function(){ console.log("As a parent I did like a parent"); } var Child = function(){} Child.prototype = new Parent(); Child.prototype.doSometh ...

Timeout error for WebSocket connection on JavaScript client

My first attempt at using websockets is not going as planned. Since my IP address changes frequently, I decided to make the following websocket call on the server-side: $echo = new echoServer("myurl.com","9000"); On the client-side, I'm making the f ...

Vue Router configuration functions properly when accessed through URL directly

I need guidance on how to handle the routing setup in this specific scenario: Below is the HTML structure that iterates through categories and items within those categories. The <router-view> is nested inside each category element, so when an item i ...

JavaScript For/in loop malfunctioning - Issue with undefined object property bug

Currently, I am tackling a basic For/in loop exercise as part of a course curriculum I am enrolled in. The exercise involves working with a simple object containing 3 properties and creating a function that takes two parameters - the object name and the it ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Holding off on triggering a jQuery Ajax request until a function returns a value

I'm currently facing an issue where an Ajax request is not waiting for a function call to return before executing. The specific scenario involves calling getSelectedMessages to retrieve checkbox values and then passing these values in an array to the ...

Passing model data from view to controller via ajax request

Upon receiving a model of type HistorySearch in my view, I am looking to resend this model to the controller using ajax: $("#exportCsv").click(function () { // get model as json var searchData = '@Html.Raw(Json.Encode(@Model))'; sear ...

Guide on how to reload the page with its initial URL after the URL has been modified using history.pushState()

After utilizing history.pushState(), I encountered an issue where the page would refresh with the current URL instead of the original one when the user refreshed the page. I attempted to detect a page refresh using methods such as cookies and hidden field ...

Enhancing Google charts with vertical line effects on hover

I am currently working on a project using google line charts and an angularjs directive. I am trying to figure out how to display vertical lines on hover, similar to how it is done on Google Trends, instead of having fixed lines. However, I have not been a ...

Activate animation upon scrolling to specific element using Material-UI

Currently building out a website using react and Material-UI, I am looking to enhance the user experience with some transitions. At the moment, I have a button set up to display a component, but I want it to show up when I scroll to that specific part of ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Guide on how to start the Bootstrap 4.6 collapse feature using JavaScript

The Bootstrap 4.6 documentation states that the collapse menu can be enabled/initialized using either data- attributes or JavaScript. It is assumed that data-target is still required to link a button to the collapsible element. This leaves us with data-tog ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

The body request has been divided into various logs

I am currently working on a JavaScript project running with GCP app engine, and I have encountered an issue with the req.body of a webhook request. To check the logs, I am using the gcloud app logs tail -s command. When I run console.log(req.body), the ou ...