You can use a counter and the remainder operator, giving a callback to replace
:
let counter = 0;
result = original.replace(/[*]/g, () => ++counter % 2 ? "<span>" : "</span>");
Live Example:
const original = "text *inner text 1* text2 *inner text 2*";
let counter = 0;
const result = original.replace(/[*]/g, () => ++counter % 2 ? "<span>" : "</span>");
console.log(result);
That works because 1 % 2
is 1
which is truthy, but 2 % 2
is 0
which is falsy, and 3 % 2
is 1
which is truthy...
Another approach would be to use a regular expression to search for matches between two *
, using a capture group to capture the matches:
result = original.replace(/\*(.*?)\*/g, "<span>$1</span>");
Live Example:
const original = "text *inner text 1* text2 *inner text 2*";
let counter = 0;
const result = original.replace(/\*(.*?)\*/g, "<span>$1</span>");
console.log(result);
That's assuming it's really okay to work purely on the basis of alternating *
characters.