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
2 Answers 2
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
trincot
357k38 gold badges282 silver badges340 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Heretic Monkey
Certainly this is a dupe...
cmgchess
now OP has a new question: what is a regular expression :D
trincot
Just in case: what is a regular expression
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
Tim Biegeleisen
526k32 gold badges324 silver badges399 bronze badges
4 Comments
Veer Thakrar
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
Tim Biegeleisen
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.Veer Thakrar
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?
Tim Biegeleisen
This answer should work just the same already.
lang-js