0

I am trying to make a script that should replace strings. This is what my current replace function does:

let message2 = message1.replace(/hello/g, "[size=medium]h[/size]ello");

As you can see, this adds the size=medium tag to the h of the word. This works good, but I want this to work in every possible capitalization and still remain in that capitalization.

For example: "hELLo" should be replaced with "[size=medium]h[/size]ELLo"

and

"HELLo" be replaced with "[size=medium]H[/size]ELLo"

Only the h/H should be wrapped in the tag, but I am not sure how to perform something like this. Big thanks for any input on this!

4
  • You mean "HELLo" be replaced with "[size=medium]H[/size]ELLo"? Commented Jul 14, 2019 at 2:01
  • Yes you are correct. Sorry i realized this just now as well @CuongLeNgoc Commented Jul 14, 2019 at 2:01
  • Possible duplicate of Replace first character of string Commented Jul 14, 2019 at 2:14
  • Are you looking to do this only for the word "hello" and any variations of it, or do you mean to do this for every word? Also can you clarify what you mean by "word"? Commented Jul 14, 2019 at 2:15

2 Answers 2

2

You can use capture groups:

message1.replace(/(h)(ello)/ig, "[size=medium]$1[/size]$2")

Or alternatively, look-ahead:

message1.replace(/h(?=ello)/ig, "[size=medium]$&[/size]")
Sign up to request clarification or add additional context in comments.

3 Comments

In case of message1 = "ahello", it still replace the h letter.
But the question is replace the first letter.
@CuongLeNgoc h is the first letter of the string hello.
1

You can try this regex:

var a = 'hello';
var b = 'HEllo';

console.log(a.replace(/^h/i, "[size=medium]$&[/size]"))
console.log(b.replace(/^h/i, "[size=medium]$&[/size]"))

Of if you just want to replace h in hello, you can use look ahead:

var a = 'HEllo';
var b = 'Halo';

console.log(a.replace(/^h(?=ello)/i, "[size=medium]$&[/size]"))
console.log(b.replace(/^h(?=ello)/i, "[size=medium]$&[/size]"))

1 Comment

Because the capture group is the full match, you can use $& instead (and remove the capture group entirely). If it's desired to only replace hs which end in ello you can lookahead for the ello

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.