27

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?

4

4 回答 4

44

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.

于 2013-04-22T00:10:39.950 回答
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.

于 2013-04-22T00:12:44.703 回答
3

Using the string .replace method will do.

.replace(/\$\$(.*?)\$\$/g, '<I>$1</I>')
于 2013-04-22T00:10:08.123 回答
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>');
}
于 2013-10-31T13:18:52.333 回答