The following statement in JavaScript works as expected:
var s1 = s2.replace(/ /gi, '_'); //replace all spaces by the character _
However, to replace all occurrences of the character . by the character _, I have:
var s1 = s2.replace(/./gi, '_');
But the result is a string entirely filled with the character _
Why and how to replace . by _ using 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')
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.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.
The . character in a regex will match everything. You need to escape it, since you want a literal period character:
var s1 = s2.replace(/\./gi, '_');
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