Skip to content
Programming Updated Dec 2017

How to replace all occurrences of a string in jQuery or JavaScript

JavaScript’s replace() only changes the first match. Here is how to replace every occurrence of a string in JavaScript or jQuery with a global regex.

Published
Reading time
1 min read
Views
7.6k views
How to replace all occurrence of a string in jQuery or Javascript

This is a surprise problem with JavaScript replace() function that is replace only first occurrence of string. But many times we want to replace a particular occurrences of whole string at once. So, now i will told you a simple method to replace all occurrence of a string with online code in jQuery and JavaScript.

var str = "Javascript and jQUery is my life"; //example string
str = str.replace(/\ /g, '-');  // this code will replace all spaces with -
alert(str);

The above code will return a string like
Javascript-and-jQUery-is-my-life

Questions & comments

Did this work for you, or did you hit a different error? Ask below and we will help.

Comments are reviewed before they appear.

More like this

More in Programming

Programming

Change Color of An Image In JAVA

In this article we will learn how to Change Color of An Image In JAVA language. This is too much easy tutorial for beginners. BufferedImage img = new BufferedImage(600, 3…

Programming

Easy Way To Draw Line On Image in JAVA

In this article you will learn how to draw line on an image in JAVA language. This is very easy way. You also can store this image in your System. BufferedImage img = new…

Programming

How to Add ArrayList into Another ArrayList Java Code

In this tutorial you will learn How to Add ArrayList into Another ArrayList Java Code. Very simple program for beginners. ArrayList<arraylist nteger="">> nodes = new Arra…