Javascript string functions

Let's see how to use replace() function for replacing string with another one. The specialty here is the usage of regular expressions to replace the string if it occurs more than once in the source string.

replace('aa','a'); is gonna replace only the first occurrence of the 'aa'.
replace(/aa/g, 'a') will replace all occurrences of the 'aa' string.
replace(/A/i, 'b') will replace the occurrences of 'A' or 'a' with 'b' - case insensitive.

Very common problems are the special character replacement. These characters should be escaped using \.

replace(/\./g, '') will replace all occurrences . with an empty ('') string.

No comments:

Post a Comment