lak
lak

Reputation: 534

Replace all the ocurrence of a string (Keep the uppercase and lowercase words) Javascript

I'm trying to replace all the occurrence of a word in a string, the first problem that I had was to replace a uppercase word or lowercase work (fixed with a regular expression), however I need to replace that word for the same word adding some HTML tags, I was able to do it, but when I replace them does not keep the uppercase or lowercase letter. like this:

var string = "Hello, hello, HELLO";
search = "hello";
replacement = "<h1>hello</h1>";    
string.split(new RegExp(search,"i")).join(replacement);

And I get this:

<h1>hello<h1>, <h1>hello<h1>, <h1>hello<h1>

However I need to maintain the uppercase or lowercase. I need something like this:

<h1>Hello<h1>, <h1>hello<h1>, <h1>HELLO<h1>

Upvotes: 0

Views: 304

Answers (1)

yrv16
yrv16

Reputation: 2275

string.replace(new RegExp('(' + search + ')',"ig"), '<h1>$1</h1>');

You can do something like that.

Upvotes: 2

Related Questions