0

Hi I'm trying to write jQuery replace function that will replace specific text in the HTML to make a class.

I have find jQuery and Html. See this fiddle: http://jsfiddle.net/davidThomas/juTtG/20

It replaces a text character inside the brackets with <b>hello world!</b>

It's good, but I'm trying to replace more different text, like below:

I have Modified jQuery:

// this
var content = $("body").text().replace(/(\[this\])([\s\S]*)(\[\/this\])/gi,'<b>$2</b>');
console.log(content);
$("body").html(content);

// another
var content = $("body").text().replace(/(\[another\])([\s\S]*)(\[\/another\])/gi,'<b>$2</b>');
console.log(content);
$("body").html(content);

// more
var content = $("body").text().replace(/(\[more\])([\s\S]*)(\[\/more\])/gi,'<b>$2</b>');
console.log(content);
$("body").html(content);

Modified HTML:

[this]hello world 1![/this] [another]hello world 2![/another] [more]hello world more![/more]

See modified problem :http://jsfiddle.net/juTtG/384

The problem is it replaces replace one text character inside the <b></b> I'm trying to replace more different text. How to make this modified jQuery and HTML work.

Another matter is, is it possible to replace by this:

<div class="body"> Add a [newclass] </div>

To:

<div class="body">Add a <b class="newclass"></b> </div>

I'm hoping someone could give me a couple suggestions as what to try.

Thanks in advance.

1 Answer 1

1

Following your "Modified HTML" problem, see this updated fiddle

Here's the modified script:

$(document).ready(function() {    
    var content = $("body")
        .text()
        .replace(/(\[[\s\S]*?\])/gi, '<b>')
        .replace(/\[\/[\s\S]*?\]/gi, '</b>');
    $("body").html(content);
});

It turns this:

[this]hello world 1![/this] [another]hello world 2![/another] [more]hello world more![/more]

into this:

  <b>hello world 1!<b> <b>hello world 2!<b> <b>hello world more!<b>

For this:

<div class="body"> Add a [newclass] </div>

see this fiddle

Using this script:

$(document).ready(function() {    
    var content = $("body")
        .text()
        .replace(/\[([\s\S]*?)\]/ig, '<b class="$1"></b>');
    $("body").html(content);
});

Makes it this:

<div class="body">Add a <b class="newclass"></b> </div>

HTH,

-Ted

Sign up to request clarification or add additional context in comments.

2 Comments

Woo nice. But how <div class="body"> Add a [newclass] </div> To: <div class="body">Add a <b class="newclass"></b> </div>
Added that to the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.