Javascript regex match and replace

38
March 09, 2019, at 08:40 AM

I have currently this type of regex replacement function

var regex = new RegExp(value, 'gi');
var return = item.replace(regex, function(match) { return "<strong>" + match + "</strong>" });

e.g.

value = 'a';

where

item = 'Cat Dog Apple';

It returns = 'Cat Dog Apple';

What I want

  • match only at start of word
  • match non-case sensitive
  • make strong whole word, not only letter

So result should be

Cat Dog '<strong>Apple</strong>'
Answer 1

You are looking for

\ba\w+

See a demo on regex101.com. In JavaScript:

let items = ['Cat', 'Dog', 'Apple', 'advertisement', 'New York']; 
let regex = /\ba\w+/gi; 
 
items.forEach(function(item) { 
    let new_item = item.replace(regex, function(match) { 
        return "<strong>" + match + "</strong>"; 
    }); 
    console.log(new_item); 
});

READ ALSO
GET request with different mongo find results on same page

GET request with different mongo find results on same page

I would like my website to have a search bar in the top section that returns a single document (ink) from a mongo databaseOn the same page, I would like to be able to access all documents from the same database

24
Applying Pandas style between two dataframes differences

Applying Pandas style between two dataframes differences

I've seen a lot of questions about finding the differences between two pandas dataframes, however here i'm trying to apply a PandasStyle difference between two dataframes

29
How to format numbers in HTML Body for automated emails on Google Apps Script

How to format numbers in HTML Body for automated emails on Google Apps Script

I'm trying to format numbers in the automated email I created on Google Apps ScriptI'm pulling numbers from an existing Google Sheets

24
Scope not what I expect when using Pandas

Scope not what I expect when using Pandas

I want to input df into a function, call the output another dataframe 'df_fn', and have df be unchangedHow do I do that?

32