Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery String Replace With Regex

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?

like image 328
Zach Avatar asked Apr 22 '13 00:04

Zach


People also ask

How to replace part of string in JavaScript?

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.

How do you replace all occurrences of a character in a string in JavaScript?

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')

How to replace All occurrences of with in JavaScript?

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.

How do I replace a character in a string?

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.


1 Answers

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.

like image 98
tckmn Avatar answered Sep 22 '22 05:09

tckmn