Str replace in jquery

Once I was trying to replace a character with another character in client side. I was trying to replace space with dash and started with replace(‘ ‘, ‘-‘) method but I was not accepting the result. It was only working one time, I mean replace() method replaced only first character but not all.

The Problem

Problem is to replace all the related characters with a specific character. Here you will see how to replace space with dash or underscore character.

The Solution

You can use str.replace(/ /g, “-“) or str.split(‘ ‘).join(‘-‘) to achieve this. Let’s see this with a simple example.


Use this simple code to replace space with dash. You can use any of the line to do your job.

        $(document).ready(function () {
            var str = "John Sara Tom";
            alert(str.replace(/ /g, "-"));
            alert(str.split(' ').join('-'));
   // Output is John-Sara-Tom

Hope this helps you.