UserIsCorrupt
UserIsCorrupt

Reputation: 5025

Replace all instances of special character

 var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]';

How can I replace every instance of [b] with <b> and every instance of [/b] with </b> in jQuery?

I was attempting to do it with regex but I couldn't get it to function properly.

Upvotes: 1

Views: 4604

Answers (4)

Ωmega
Ωmega

Reputation: 43673

Elegant way:

whatever = whatever.replace(/\[(\/?)b\]/g,'<$1b>');

See and test it here.

Upvotes: 3

jackwanders
jackwanders

Reputation: 16020

With regex, it'd be:

whatever = whatever.replace(/\[b\]/g,'<b>').replace(/\[\/b\]/g,'</b>');

That'd seem to be the easiest solution

Upvotes: 1

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

whatever = whatever.replace(/\[b\]/g, '<br>').replace(/\[\/b\]/g, '</b>');

DEMO

Upvotes: 0

Oliver Tappin
Oliver Tappin

Reputation: 2541

string.replace("[b]", "<b>");

Failing that, you could use PHP to do it using str_replace if it's being uploaded to a database.

Upvotes: 0

Related Questions