Replacing strings between | | with RegEx using JavaScript

Viewed 51

I am fetching some data from an API. One of the results is this string:

| Experience Points | Level | Proficiency Bonus |

I've been trying to use RegEx with replace() to have each string between | | in a tag. So far I was able to have the first and last inside the tag, but I fail to have the middle string inside the tag. Can someone point out what I am doing wrong and maybe help me with a solution? I've been stuck on this for days. I'd really appreciate it.

This is what I have done so far:

replace(/\|\s(\D*?)\|/g, "<span>$1</span>")

It gives me the following result:

<span> Experience Points </span> Level <span> Proficiency Bonus </span>

This is what I expect:

<span> Experience Points </span> <span> Level </span> <span> Proficiency Bonus </span>

Thank you all for the help.

2 Answers

const input = "| Experience Points | Level | Proficiency Bonus |";
const output = input.split(/\s*\|\s*/).filter(s => s.length > 0).map(s => `<span>${s}</span>`).join("");
console.log(output);

...or simply:

const input = "| Experience Points | Level | Proficiency Bonus |";
const output = input.replaceAll(" | ", "</span><span>").replace("| ", "<span>").replace(" |", "</span>");
console.log(output);

If you need spaces between the <span>s, then:

  • in the 1st solution, replace .join("") with .join(" "), and
  • in the 2nd solution, replace "</span><span>" with "</span> <span>".

Using your RegEx pattern...

Do it in 2 passes:

// 1st pass
var str = "| Experience Points | Level | Proficiency Bonus |";
var intermediateResult = str.replace(/\|\s(\D*?)\|/g, "</span> <span> $1</span> <span>");

// intermediate result:
// </span> <span> Experience Points </span> <span> Level </span> <span> Proficiency Bonus </span> <span>

// 2nd pass
var result = intermediateResult.replace(/^(<\/span> )|( <span>)$/g, "")

// result:
// <span> Experience Points </span> <span> Level </span> <span> Proficiency Bonus </span>

or in 1 line:

var str = "| Experience Points | Level | Proficiency Bonus |";

var result = str.replace(/\|\s(\D*?)\|/g, "</span> <span> $1</span> <span>").replace(/^(<\/span> )|( <span>)$/g, "")

Using a different RegEx pattern:

var result = str.replace(/\|/g, "<span> </span>").replace(/^<span>|<\/span>$/g, "")
Related