Pair a specific portion of text with another string

I'm having trouble finding a substring within a string. The substring and the string are as follows:

var str="My name is foo.I have bag(s)"
 var substr="I have bag(s)"

When I use str.match(substr), it returns null, probably because the match() function expects a regular expression input and gets confused with the '('. I tried using '\' before the round brackets, but it didn't work. The indexOf() function does work, but unfortunately, I am not allowed to use it. I also attempted using test() and exec(), but without any success.

Answer №1

For modern engines, you can easily utilize the String.prototype.includes method:

str.includes( substr )

If you need a solution that is compatible with older browsers and want to steer clear of using String.prototype.indexOf, you can create your own `includes` function by manually iterating through the string:

String.prototype.includes = function ( substr, start ) {
    var i = typeof start === 'number' ? start : 0;
    // Exit early if there are not enough characters left in substr for j to reach its length
    for ( var j = 0; i + substr.length < this.length + j + 1; ++i ) {
        j = substr[j] === this[i] ? j + 1 : 0;
        if ( j === substr.length )
            return true;
    }
    return false;
};

If you absolutely must use a regex test, you can follow the guidance from this particular answer to properly escape the substring for regex usage. This involves adding a backslash before certain characters like parentheses:

new RegExp( substr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') ).test( str )

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

Issue: Exceeding rendering limit. React has a restriction on the number of renders to avoid endless loops

I'm in the process of creating a basic to do list using React, and I've encountered an issue with the handleSubmit() function that I can't seem to resolve. import React, { useState } from "react"; function TaskList() { const [ta ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

JQuery ajax DELETE request encounters issues during the OPTIONS stage

I'm encountering an issue while trying to send a delete request using JQuery as it consistently results in a 500 internal server error. Here's the code snippet I'm using for the request: $('#deleteReview').click(function(event, ui ...

What is the best way to showcase a PDF file on a webpage with multiple thumbnails using JavaScript or jQuery?

I recently undertook a project at work that involved displaying multiple PDF thumbnails/images on a webpage. These files were dynamically loaded from a directory on my system. Each thumbnail corresponded to a PDF file stored in a different directory. My g ...

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

Tips for implementing an onClick event within a NavBar component in a React application

Embarking on my first React project has been an exciting journey for me. I am relatively new to JavaScript, HTML, CSS, and the world of web app programming. My goal is to showcase some information upon clicking a button. In my main default component, App ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Creating routes in Node.js after setting up middleware

Currently tackling a project using node.js and encountering a specific issue. After setting up all routes with express (app.get("..", func)), I find myself stuck with a middleware that catches all requests and redirects to a 404-page. The problem arises w ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

The Ajax Process continues to run even after the user has navigated away from the page

Currently, I have a JavaScript function that refreshes a specific section of a Rails-generated view every 2.5 seconds using a JS request to update a basic progress bar. function refreshPage(){ $.ajax({ type:"GET", dataType:"script" }) } s ...

When rendering in React, the output of a multidimensional object may appear as undefined

Currently experiencing a challenge with a React application that I am developing. I am attempting to display data on the screen, however, there are instances where an object key is not available. For example: <div> <TableRow> <TableCel ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...