Pascal Stockert
Pascal Stockert

Reputation: 366

Wrapping certain words by replacing '`' with tags

I'm trying to copy a bit of "markdown-behaviour". I'm trying to feed JS some text, for example, a string like so:

"This is some very very fancy `code example` to try out yourself!"

I want to replace the starting ` with <div class="code"> and the terminating ` with "</div>" in order to highlight some stuff. I've tried doing it with .replace() but can't get it to work without it including the text after the terminating `.

Am I doing something fundamentally wrong here? Are there more elegant solutions other than manually going through the String char by char?

Many thanks Pasu-

Upvotes: 1

Views: 52

Answers (3)

Maxim Palenov
Maxim Palenov

Reputation: 720

You can use this invocation to replace something with <div class="code">something</div>:

someString.replace(/`([^`]*)`/, (match, p1) => `<div class="code">${p1}</div>`);

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

You can try to use regex to replace it.

var str = 'This is some very very fancy `code example` to try out yourself!';

document.body.innerHTML += str.replace(/`(.*)`/, '<div class="code">$1</div>')
.code {
  color: red;
}

(.*) means: any character one or more times.

$1 means: the content of the first group (which inside ())


Or if you want to replace more than 1 time, you can try this.

var str = 'This is some `code example 1` and very very fancy `code example 2` to try out yourself!';

document.body.innerHTML += str.replace(/`(.*?)`/g, '<div class="code">$1</div>')
.code {
  color: red;
}

Upvotes: 3

mortb
mortb

Reputation: 9859

Try this:

var x = "Hello `code` World!".replace(/`([^`]+)`/g, "<div class='code'>$1</div>");

console.log(x);

Upvotes: 4

Related Questions