2

I'm trying to replace all mentions of [b] in a text string and replace it with <b>. The problem with what I'm using below this that it's replace every [b] on the page, and I only want it to change the [b]'s within the text string ("text") that I'm sending in.

Taking out the 'g' for global in the regex doesn't work very well because it then doesn't replace them all...

text = $("#input").val();

text = text.replace(new RegExp('(^|\\s|>)\\[b](\\S.*?\\S)\\[/b]($|\\s|<)', 'gim') , '$1<strong>$2</strong>$3');

any ideas? Thanks

5
  • Try text = text.replace(/(^|\s|>)\[b\](.*?)\[\/b\]($|\s|<)/gim, '$1<strong>$2</strong>$3'); Commented Nov 19, 2011 at 10:01
  • What do you mean by "on the page" and "within the text string"? The replace is operating on your text variable, so if that variable holds the whole page obviously it'll do replacements within the whole page. How do you set text before doing the replace? Commented Nov 19, 2011 at 11:14
  • it's either an input value or text of an element I'm passing in via jquery.text() Commented Nov 19, 2011 at 12:03
  • 2
    @Tim Yes, can you post a couple of reasonable input examples? Or should we invent them ourselves? Until you do that, you will get no answer. Commented Nov 19, 2011 at 12:04
  • @Tim Your regex is doing well: jsfiddle.net/avrelian/2eygB. The problem is somewhere else. Try defining your text variable in the local scope. Commented Nov 21, 2011 at 10:44

1 Answer 1

1

I'm not exactly sure what the problem is because the question is a bit unclear. Are you trying to replace the content within the textarea with the new html tags?

The following code is currently working for me in production:

text = $("#contract_body").val();  // strore the current contents
text = text.replace(/\[b\](.*?)\[\/b\]/gim, "<strong>$1</strong>");  // replace bbcode with html tags
$("#contract_body").val(text);  // update the textarea with the new string contents

I hope that helps.

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

Comments

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.