Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all characters in a string using JavaScript for this specific case: replace . by _

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?

like image 799
Kevin Le - Khnle Avatar asked Jun 23 '10 15:06

Kevin Le - Khnle


People also ask

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 do you replace a certain part of a string 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.

What is replace () in JavaScript?

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.

How do I replace multiple characters in a 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.


1 Answers

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, '_');
like image 193
Jacob Mattison Avatar answered Oct 13 '22 21:10

Jacob Mattison