JavaScript replace all Word | space, comma | special characters

You can do modifications on a string using JavaScript replace method. replace method is an inbuilt function in JavaScript which is used to change particular character, word, space, comma, or special char in Strings.

How it’s work?

The replace() method find a string for a specified input, or a regular expression, and returns a new string where the specified input is replaced.

Syntax

string.replace(searchvalue, newvalue)

JavaScript replace String Example

In the example, we are replacing a “JS” word with “JavaScript”.

<!DOCTYPE html> 
<html> 
	<script> 

    var string = 'EyeHunts Tutorial JS'; 
	var newstring = string.replace(/JS/, 'Javascript'); 
   
	document.write(newstring); 
  
</script> 

<body> 

</body> 
</html> 

Output: EyeHunts Tutorial Javascript

JS replace all spaces in Strings

var result = replaceSpace.replace(/ /g, ";");

More examples: – JavaScript Remove whitespace of String | Beginning & End

JS replace all commas in Strings

The best way is to use regular expression with g (global) flag.

var myStr = 'this,is,a,test';
var newStr = myStr.replace(/,/g, '-');

console.log( newStr );  // "this-is-a-test"

Q: How to Replace multiple strings with multiple other strings in Javascript?

Answer: If you want to replace multiple characters in one replace the call then use a function to replace each one.

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

Source: https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings

Q: How to replace special characters in a string?

Answer: For example string is:

string = "img_realtime_tr~ading3$"

You want to remove special characters from a string and replace them with the _ character.

The resulting string should look like “img_realtime_tr_ading3_”;

I need to replace those characters: & / \ # , + ( ) $ ~ % .. ' " : * ? < > { }

Then see below the solution code.

<!DOCTYPE html> 
<html> 
	<script> 

    var string = 'img_realtime_tr~ading3$'; 
	var newstring = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
   
	document.write(newstring); 
  
</script> 

<body> 

</body> 
</html> 

Output:

Javascript replace special characters in a string

Do comment if you have any doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.