Please enable Javascript for better experience...
How to replace Space with Dash or Underscore in JQuery
By Rahul Kumar Jha | Mar 7, 2015 | In Tips | Total Views [ 17104 ]
Taged In
(2 Like)
Rate

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.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors