sending parameters into a regex within a function

Struggling to pass a variable into a robust regex, managing to make it work outside the function but unable to figure out how to get it working within a function. Not sure why match[1] is returning null or how to find words after a keyword.

Here's what I've tried so far:

var s = 'match my word after this word';
function returnWordAfter(theSentence, theWord){
  var TheRegEx = new RegExp("/"+theWord+"\s(\w*)/");
  var matches = theSentence.match(TheRegEx, '');
  return matches[1];
}
var matchedWord = returnWordAfter(s, "this");
console.log(matchedWord);

Answer №1

Avoid using forward slashes ("/") and escaping backslashes ("\") in the code:

new RegExp(keyword + "\\s(\\w*)");

var keyword = "hi";
var regExpPattern = new RegExp(keyword + "\\s(\\w*)");
"hi there".match(regExpPattern) // => ["hi there", "there"]

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

Ways to initiate state transition from child component to parent component using React Hooks?

In the parent component, I have the following: const [updateQuantity, quantity] = useState(1); const handleChangeQuantity = e => { console.log(e.target.value); console.log("TEST"); updateQuantity(e.target.value); }; I the ...

Updating entire DOM in javascript

Implementing undo-redo functionality in my project has proven to be quite complex, as every change affects numerous elements. I believe that saving and restoring the entire page may be the most effective solution. However, I have encountered issues with mi ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

What is the best way to save website information in SQL Server?

My website is www dot abc dot com and it contains some valuable content that I want to store in SQL Server. Can this be done using DOM? If not, please recommend alternative methods. I've searched this forum for similar solutions but haven't found ...

Node.js error: HTML audio file returns 404 on server but plays fine when accessed directly as an HTML file

I'm facing an issue with an HTML page that contains an autoplay tag for a song (the file is in mp3 format). When I open the page as a local file on my Mac, the song plays fine. However, when I try to run it using a node.js file with socket.io, the son ...

Issue with integrating e-junkie shopping cart with Bootstrap 5

After transitioning from Bootstrap 4 to Bootstrap 5 and encountering navigation issues on smaller screens, I delved into the code to uncover the source of the problem. It turns out that the collapse button in the navbar wasn't functional due to confli ...

What is causing the backslash character to be removed from my ajax request?

When using Ajax to call a rest endpoint, the request takes two parameters: user and permission. $.ajax({ type: 'GET', cache: false, url: "/app/Rest/4.0/UserManagement/AddPermissionToUser", data: { username: encodeURI(user ...

Tips for effectively implementing correct reselection in a React-Redux application

I have a system that allows users to search for data based on their input. I am currently implementing reselect in my application. import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux" ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

slow loading background slideshow in css

Creating a simple slideshow for the background using CSS has been successful, but I am facing an issue with making all backgrounds utilize background-size: cover. I want the images to fit properly on the screen. Another problem is that the pictures take a ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

Webpage refreshing when resizing browser

Hey there, I'm facing an issue where my HTML website restarts whenever the browser size changes. Can someone please help me fix this? You can check out my website here I have uploaded my code files here: Code Files Link ...

Utilizing visual representations for "symbol" within eCharts4r

I have been exploring the use of the "image" option for the symbol parameter in a tree chart with eCharts4r. Despite trying multiple methods, I am struggling to assign a unique image to each node in the tree instead of using a universal one. However, my a ...

What are the best ways to conceptualize the benefits of WebRTC?

I encountered a peculiar issue with the abstraction of the WebRTC offer generation process. It appears that the incoming ice candidates fail to reach the null candidate. While I have been able to generate offers successfully using similar code in the past, ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Creating Beautiful Tabs with React Material-UI's Styling Features

I've been delving into React for a few hours now, but I'm struggling to achieve the desired outcome. My goal is to make the underline color of the Tabs white: https://i.stack.imgur.com/7m5nq.jpg And also eliminate the onClick ripple effect: ht ...

What is the correct way to implement Axios interceptor in TypeScript?

I have implemented an axios interceptor: instance.interceptors.response.use(async (response) => { return response.data; }, (err) => { return Promise.reject(err); }); This interceptor retrieves the data property from the response. The re ...

Mistakes in my async/await workflow: How am I incorrectly loading and injecting this external script?

Encountering a simple problem: some calls to refresh() cause window.grecaptcha to become undefined. It doesn't happen all the time, probably due to network delays. Debugging this issue is proving to be tricky, especially since I'm still new to th ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...