Regular Expressions are a very handy tool in a developer's arsenal. They can be used to do string replacements quite easily. However, regexes can be daunting at first since the regular expressions can look just like garbled text. But simplicity beats all and I want to show you a simple use of Regular Expression for string replacement. Sample this:
var text = "This is a test text. And I have a fish.";
alert(text.replace(/(fish)/g, "gold $1"));
What does the above do? /(fish)/g
is the regular expression for strings of the form "fish". The replacement string just replaces it with gold fish. Here $1 represents the first match. First I say because, fish is enclosed in parenthesis. If there were more expressions enclosed in ()
, then they would be matched witch $2, $3 and so on. $0, as you might wonder, represents the entire matched string.
Something useful would be to do BBcode replacements like the following:
text = text.replace(/[b]([\S|\s]*?)[\/b]/g, "<span class='boldText'>$1</span>");
The above replaces text enclosed with [b]
with real HTML tags.
These are the simplest of cases where Regexes come in real handy. You can experiment with Regexes at this cool site called Regex101.com (Link