Home > Back-end >  Need to replace a character in a string with two new values
Need to replace a character in a string with two new values

Time:10-27

var Str = "_Hello_";
var newStr = Str.replaceAll("_", "<em>");
console.log(newStr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related