0

var Str = "_Hello_";
var newStr = Str.replaceAll("_", "<em>");
console.log(newStr);

it out puts <em>Hello<em> I would like it to output <em>Hello</em> but I have no idea how to get the </em> on the outer "_", if anyone could help I would really appreciate it. New to coding and finding this particularly difficult.

depperm
10.8k4 gold badges46 silver badges68 bronze badges
asked Oct 26, 2021 at 16:17
0

2 Answers 2

3

Replace two underscores in one go, using a regular expression for the first argument passed to replaceAll:

var Str = "_Hello_";
var newStr = Str.replaceAll(/_([^_]+)_/g, "<em>1ドル</em>");
console.log(newStr);

NB: it is more common practice to reserve PascalCase for class/constructor names, and use camelCase for other variables. So better str =, ...etc.

answered Oct 26, 2021 at 16:21
Sign up to request clarification or add additional context in comments.

3 Comments

Certainly this is a dupe...
now OP has a new question: what is a regular expression :D
0

I would phrase this as a regex replacement using a capture group:

var str = "_Hello_ World!";
var newStr = str.replace(/_(.*?)_/g, "<em>1ドル</em>");
console.log(newStr);

answered Oct 26, 2021 at 16:21

4 Comments

Thank you very much that code works, just to better my understanding, would you be able to explain the (.*?) and 1,ドル as I have not seen this before
The 1ドル in the replacement is called a capture group, and it refers to the (.*?) term in the regex pattern, which is whatever sits in between the underscores.
Thank you, so if I wanted to apply it to a larger string, with words that both have and don’t have underscores, what would I have to change?
This answer should work just the same already.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.