Helping ordinary people create extraordinary websites!
   

How can I do a JavaScript string replace on a specific character in a string?

Tuesday, 1st September 2009
by ToMas


For example I have the string "I am - the text" and I would like to replace the "- " in my string with "". How can I do this replace with JavaScript?





Vader
Hi Tomas,
In order to replace any portion of a string using JavaScript you would use the JavaScript replace method that is included in the JavaScript String object.

This method serves to be a very useful one as I myself have used it countless amounts of times.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
replace()
Replaces specified character with other characters in a string.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

To demonstrate how it works first we need to create our string that we will be manipulating.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
var strDemo = "I am now learning how to replace characters in a string using JavaScript.";
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

*Note: String replace methods by default will replace only the first instance of the matching string. To replace all instances you will need to create a loop to go through the string until all instances are replaced.

To use the replace() method you will need to identify:
1. what will be replaced as well
2. what it will be replaced with.

Below you will find the syntax.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
var strDemoReplaced = strDemo.replace( "What will be replaced", "What it will be replaced with" );
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Here is an actual example:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
var strDemo = "I am now learning how to replace characters in a string using JavaScript.";

var strDemoReplaced = strDemo.replace( "JavaScript", "PHP :-)" );

document.write(strDemoReplaced);
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

The output of this will be:

"I am now learning how to replace characters in a string using PHP :-)."

Minus the quotes ofcourse, and, if the initial string were

"I am now learning how to use JavaScript to replace characters in a string using JavaScript."

The output would be:

"I am now learning how to use PHP :-) replace characters in a string using JavaScript."

Happy Replacing!
Wednesday, 14th October 2009
Votes:
56
39

More JavaScript Help:
» How do I place an image on a button using the document object
» How do I submit a form by clicking on a link with JavaScript?
» How to submit a form using JavaScript?
» How can I create Facebook applications?
» How to redirect user to different pages depending on time
» How to remove special characters from a string?
» How can I count the length of string with JavaScript?
» Displaying content by using checkboxes with Java Script

SPREAD THE WORD!
Tell a Friend

GET OUR NEWS


Developer Resources