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.

Code

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

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

Hope this helps you.

ref: http://dotnet-concept.com/Tips/2015/3/5798821/How-to-replace-Space-with-Dash-or-Underscore-in-JQuery

Leave a Reply