1001Songs Clips
1001Songs Clips

Reputation: 59

Quote comments with replace

I need to transform this:

[quote=mvneobux]My first comment[/quote]
I liked your comment.

In that:

<div class="quote">
    <div class="author">mvneobux:</div>
    My first comment.
</div>
I liked your comment.

My solution:

comment.replace('#\[quote=(.+?)\](.+?)\[/quote\]#', '<div class="quote"><div class="author"> $1 </div> $2 </div></blockquote> texto: $2'),

But it just doesn't work. Can you help me ?

Upvotes: 1

Views: 44

Answers (4)

Your regex has a problem.

#\[quote=(.+?)\](.+?)\[/quote\]#
  • #: matches the character # literally. But, your string has not the character. You have to delete the character.
  • /: pattern error in Javascript. You have to add backslash to escape the character.

So, your regex should be following syntax.

\[quote=(.+?)\](.+?)\[\/quote\]

var string = `[quote=mvneobux]My first comment[/quote]
I liked your comment.`;
var result = string.replace(/\[quote=(.+?)\](.+?)\[\/quote\]/, '<div class="quote"><div class="author"> $1 </div> $2 </div></blockquote> texto: $2');

console.log(result);

Upvotes: 2

AMD
AMD

Reputation: 203

Try this:

let reg = /\[quote=(.*?)\](.*?)\[\/quote\]/g;

let str = '[quote=mvneobux]My first comment[/quote]';

let result = str.replace(reg, '<div class="quote"><div class="author"> $1 </div> $2 </div>');

console.log(result) // "<div class="quote"><div class="author"> mvneobux </div> My first comment </div>"

Upvotes: 0

Aks Jacoves
Aks Jacoves

Reputation: 877

One alternative:

let str = `[quote=mvneobux]My first comment[/quote]
I liked your comment.`

let result = str.replace(/(?:\[quote=)(.*?)(?:\])(.*?)\[\/quote\]/, '<div class="quote"><div class="author">$1:</div>$2</div>')

console.log(result)

Upvotes: 0

GirkovArpa
GirkovArpa

Reputation: 4912

const regex = /^\[quote=(.*)\](.*)\[\/quote\]\n(.*)/;
const string = `[quote=mvneobux]My first comment[/quote]
I liked your comment.`;
const replacement = `<div class="quote">
    <div class="author">$1:</div>
    $2
</div>
$3`;
const result = string.replace(regex, replacement);
console.log(result);

You can also see it here: https://regex101.com/r/3CRrP8/1

Upvotes: 0

Related Questions