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,606
  • 4
  • 43
  • 67

2 Answers2

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 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 – Veer Thakrar Oct 26 '21 at 16:51
  • 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. – Tim Biegeleisen Oct 26 '21 at 16:52
  • 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? – Veer Thakrar Oct 26 '21 at 17:11
  • This answer should work just the same already. – Tim Biegeleisen Oct 26 '21 at 22:14