Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string.

The original string I have is "Hello This is world This".

Here is the code snippet I have tried:


var patt = 'Hello This is world This'
var res = patt.constructor;
alert(patt.replace(new RegExp('('This')', 'gi'), "<b>$1</b>"));

Unfortunately, my attempts to format the text as needed have not been successful.

Essentially, what I need to do is bold all words in the string except for "This".

If anyone could provide some assistance or guidance on how to achieve this, it would be greatly appreciated.

Thank you for your help!

Answer №1

To implement a negative lookahead, use the code below:

var sentence = 'Hello This is world This'
sentence.replace(/\b(?!this\b)(\w+)\b/gi, "<b>$1</b>")
# '<b>Hello</b> This <b>is</b> <b>world</b> This'

You can also achieve this by using RegExp:

> sentence.replace(new RegExp("\\b(?!this\\b)(\\w+)\\b", "gi"), "<b>$1</b>")
'<b>Hello</b> This <b>is</b> <b>world</b> This'

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

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Endless loop issue in Reactjs encountered when utilizing React Hooks

Delving into React Hooks as a newcomer, I encountered an error that has me stumped. The console points to an infinite loop in the code but I can't pinpoint the exact line responsible. Too many re-renders. React limits the number of renders to prevent ...

Why won't my Java servlet code execute?

included the directory structure To facilitate adding two numbers and displaying the result upon clicking a submit button, I developed a straightforward Java servlet. This servlet retrieves the necessary information when called. The development environmen ...

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

Stuck on an endless loop of the Ionic splash screen

Currently, I am facing an issue with my Ionic 1 project. Everything was functioning properly until a few days ago when the splash screen stopped disappearing on iOS, although it still does on Android. I have searched for solutions on Google but haven' ...

Identify the nested Object within the Json data

I am looking to add and name a nested object within my Json data structure. The current structure of my Json is as follows: { "MH": [ { "MHF46": "Ledig", "MHF60": "60", }, ...

What are the methods to ascertain whether an HTML element possesses a pseudo element?

Is there a method to identify whether an HTML element has a pseudo element (::before / ::after) applied to it without invoking the function: window.getComputedStyle(element, ":before/:after"); MODIFIED: the response is NEGATIVE The issue with getCompute ...

As I embarked on my journey into node.js, I encountered some stumbling blocks in the form of errors - specifically, "Uncaught ReferenceError: module is not defined"

Embarking on my Node.js journey, I am delving into the world of modules. After ensuring that both node and npm are correctly installed, I will share the code below to provide insight into the issue at hand. Within my project, I have two JavaScript files - ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

What could be causing the onclick function to not activate on the iOS safari browser?

My Shopify site works perfectly on all browsers except iOS Safari. When users try to click the "add to cart" button on this specific browser, it does not trigger the onclick function. This issue is unique to iOS Safari as the button works fine on desktop a ...

Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource. Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones. The JSON message I receive: [ {"age": 0,"id": "my first tweet","name": "H ...

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...

Converting string to JSON format by splitting it based on names

I recently manipulated a string containing the values "title:artist" by utilizing the str.split method : res = song.split(":"); The resulting output is as follows: ["Ruby","Kaiser Chiefs"] Now, I am curious about how to include the name in this array f ...

Tackling the challenge of merging PDF files and designing a Table of Contents feature reminiscent of Acrobat in Node.js and JavaScript

I am currently implementing the following code snippet: const pdfmerger = require('pdfmerger') var pdfStream = pdfmerger(array_of_pdf_paths) var writeStream = fs.createWriteStream(final_pdf_path) pdfStream.pipe(writeStream) pdfmerger(array_of_pd ...

Utilize jQuery to create a dynamic image swapping and div showing/hiding feature

I'm having trouble implementing a toggle functionality for an image and another div simultaneously. Currently, when the image is clicked, it switches to display the other div, but clicking again does not switch it back. Can someone please advise on wh ...

How can I retrieve data from a script tag in an ASP.NET MVC application?

I'm struggling to figure out how to properly access parameters in a jQuery call. Here is what I currently have: // Controller code public ActionResult Offer() { ... ViewData["max"] = max; ViewData["min"] = min; ... return View(paginatedOffers ...

A guide to breaking a string apart based on 2 or more continuous spaces in PHP

I have encountered a unique dilemma that I haven't found a solution for on Stack Overflow in regards to PHP. My task is to separate the city, state, and zip code into different variables from a given string: $new = "PALM DESERT SD63376 ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...