29

Let's say I retrieve the value of a <textarea> using jQuery. How can I then replace a portion of the value using JavaScript/jQuery. For example:

string: "Hey I'm $$zach$$"

replace $$zach$$ with <i>Zach</i>

And still keep the rest of the string intact?

1
  • I see that you've used &lt; etc in your example. Do you want to use < or &lt;? Commented Apr 22, 2013 at 0:10

4 Answers 4

48

Use a regex replace:

yourTextArea.value = yourTextArea.value.replace(/\$\$(.+?)\$\$/, '<i>$1</i>')

Explanation of the regex:

\$\$  two dollar signs
(     start a group to capture
.     a character
+     one or more
?     lazy capturing
)     end the group
\$\$  two more dollar signs

The capture group is then used in the string '<i>$1</i>'. $1 refers to the group that the regex has captured.

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

2 Comments

what if for example, I "$$hi everyone$$" to be replaced?
Do not forget 'g' after '/'. That worked when i added this letter only.
13

Use this:

str.replace(/\${2}(.*?)\${2}/g, "<I>$1</I>");
\${2} matches two $ characters
(.*?) matches your string to be wrapped
\${2} same as above
/g matches globally

jsFiddle

If you wanted something in jQuery:

$("#txt").val().replace(/\${2}(.*?)\${2}/g, "<I>$1</I>");

Markup:

<textarea id="txt">I'm $$Zach$$</textarea>

jsFiddle

Wrap it in a function for best use:

var italics = function (str) {
    return str.replace(/\$\$(.*?)\$\$/g, "<I>$1</I>");
}

italics($("#txt").val());

Seems like you want to make a syntax similar to Markdown. Why not just use a Markdown parser for your fields instead of reinventing the wheel?

Showdown JS is actively developed and you get the same Markdown syntax as with any other markdown syntax.

Comments

3

Using the string .replace method will do.

.replace(/\$\$(.*?)\$\$/g, '<I>$1</I>')

Comments

3

Use this, change link and tag for extended linkify function :

String.prototype.linkify = function() {
    var wikipediaPattern = /<wikipedia>(.+?)<\/wikipedia>/g; 
    return this.replace(wikipediaPattern, '<a href="http://fr.wikipedia.org/wiki/$1">$1</a>');
}

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.