Veer Thakrar
Veer Thakrar

Reputation: 1

Need to replace a character in a string with two new values

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.

Upvotes: 0

Views: 52

Answers (2)

trincot
trincot

Reputation: 351084

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.

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522541

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);

Upvotes: 0

Related Questions