Javascript/jquery String Replace With Regex
Let's say I retrieve the value of a
Solution 1:
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.
Solution 2:
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
If you wanted something in jQuery:
$("#txt").val().replace(/\${2}(.*?)\${2}/g, "<I>$1</I>");
Markup:
<textareaid="txt">I'm $$Zach$$</textarea>
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.
Solution 3:
Using the string .replace
method will do.
.replace(/\$\$(.*?)\$\$/g, '<I>$1</I>')
Solution 4:
Use this, change link and tag for extended linkify function :
String.prototype.linkify = function() {
var wikipediaPattern = /<wikipedia>(.+?)<\/wikipedia>/g;
returnthis.replace(wikipediaPattern, '<a href="http://fr.wikipedia.org/wiki/$1">$1</a>');
}
Post a Comment for "Javascript/jquery String Replace With Regex"