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?
replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With