Struggling with white space problems? JavaScript can come to the rescue with its regular expression feature for replacing

I am looking to utilize regular expressions in wrapping HTML tags around specific words within a text,

Below is an example using JavaScript:

In the given scenario, the first "We" is not being replaced. Why is this happening and how can it be modified?

var str="Welcome Microsoft We are Microsoft! we wehas weo in the WE world we.";
var res = str.replace(/([\s\!\.])(micro|microsoft|we)([\s\!\.])/gi, "$1<em>$2</em>$3");
console.log(res);
// wrong:Welcome <em>Microsoft</em> We are <em>Microsoft</em>! <em>we</em> wehas weo in the <em>WE</em> world <em>we</em>.
// right:Welcome <em>Microsoft</em> <em>We</em> are <em>Microsoft</em>! <em>we</em> wehas weo in the <em>WE</em> world <em>we</em>.

Answer №1

"Why is the word 'we' not replaced?"

The reason for this is that the space preceding it has already been captured by the previous match, leaving no space before "we" for the regex engine to find.

In simpler terms, your regex pattern matches an extra character after the word "we," which cannot be used for the next match.

How can we modify the regex?

A quick solution is to use a look-ahead assertion for the space check (by the way, you don't need to escape ! or . inside a character class):

str.replace(/([\s!.])(micro|microsoft|we)(?=[\s!.])/gi, "$1<em>$2</em>");

This modification will address the current issue. However, if the word is the first or last word in the input, it may not match because there is no preceding or succeeding character.

It is common practice to use a word boundary \b:

str.replace(/\b(micro|microsoft|we)\b/gi, "<em>$1</em>");

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

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...

Controlling camera rotation with threeJS Trackball

After working with threejs for quite some time on a 3D image-based modeling application at vmtklab.orobix.com, I have encountered an issue. I am currently using TrackballControls.js for camera rotation, translation, and zooming. controls = new THREE.Track ...

Customizing JSON Data Structure in jQuery DataTables for Enhanced Display

Is it possible to populate a custom JSON data structure using jQuery Datatable? I have found a solution for the default Datatable JSON structure that works well, but I would like to use my own JSON structure instead. I am currently using DataTables 1.10.7. ...

Is it possible to adjust the width of the comment box on the Facebook "Like" button?

Is there a way to set the width of the comment box that appears after clicking the Facebook "Like" button? I know how to adjust the width of the button itself and related content, but can't find any options for the comment box: I've tried overri ...

Customize data appearance in Django Admin interface

I am working with a model that has a json field. The data stored in this field may not always be pretty-printed, and I am okay with it as long as it is valid. However, when the data is displayed in Django admin, I would like it to be pretty printed for eas ...

Is it possible to dynamically change the 'amount' on a PayPal button or iframe?

My task is to create a checkout page that exclusively uses PayPal for payment processing. The challenge I face is that the purchase amount is not fixed; users can input the desired amount for their purchase (e.g. buying a £100 gift code). PayPal typicall ...

Error: Calculation of date 30 days in the past incorrect

Currently, I am in the process of developing a function that compares the current date with an expiration date. The input, expireStamp, is represented as a timestamp measured in milliseconds. compDate = function(expireStamp) { // Convert the timestam ...

Want to know how to choose a class or id when a button is clicked using jQuery?

One particular div containing a class of "vote" holds: <div class="vote"> <input type="hidden" name="q_id" class="q_id" id="q_id" q_id="{{ result.object.id }}" value="{{ result.object.id }}"> <button type="submit" class="downvote" value="do ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Steps for resolving the problem: [$sce:itype] while using AngularJS version 1.6

I'm encountering an issue with $sce while using AngularJS 1.6.4: Error: [$sce:itype] http://errors.angularjs.org/1.6.4/$sce/itype?p0=html Stack trace : L/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425 trustA ...

Confirm the length of the password meets the specified minimum and maximum requirements

I'm currently learning about Regex for the first time, as it's a topic covered in my school curriculum. The assignment I received involves using my .NET Regex Tester to search through a text for passwords. To clarify my code... The passwords sho ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

How can PHP be integrated with MaterializeJS for autocomplete functionality?

Here is my PHP code snippet: <?php require_once __DIR__ . '/../inc/_puredb.php'; $query = $db->prepare("SELECT user_name FROM users"); $query->execute(); if($query->rowCount() > 0) { $rows = array(); while($res = $quer ...

Error: The function res.json is not defined

Having trouble sending two JSON objects? Getting a TypeError: res.json is not a function error and not sure why it's happening? Any ideas on how to fix this issue? Thanks! app.post('/danger', function response(req, res) { let placeId = ...

Enhancing the angular-ui-bootstrap typeahead module

Currently, I am using the typeahead feature from angular-ui-bootstrap to allow users to select a person's name or add a new name if it is not available in the options. I have customized the getMatchesAsync function with the following code: if(scope ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

How to Halt or Keep Running a For Loop in Angular 2/4?

for (let index = 0; index < this.selectedFileType[i].count; index++) { this.modal.show(); } My goal is to display the modal each time it enters the loop, and then proceed with the loop after closing the modal. ...

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...