Search code examples
jqueryreplacewhitespacestrip

jQuery Copy text from one field to another but replacing white spaced with dashes


I have a small script for a project which i am building, and the customer has to specify a campaign title and then have to choose their own URL.

What I'd like to do is copy the campaign title, make it all lowercase, replace white spaces with hyphens and remove punctuation marks like £$%!?. etc.

So when someone inputs into the campaign title:

This Is my Awesome Campaign!

it replaces it in the URL field with

this-is-my-awesome-campaign

Here's a fiddle i've got that just copies it from the title to the URL field. I'm just not sure on how to do strip and punctuations and remove white spaces

https://jsfiddle.net/q82o3kvv/


Solution

  • I guess you want special characters gone too:

    $(function() {                                                   
        $("#inputCampaignTitle").change(function() {                    
            $('#inputUrl').val($('#inputCampaignTitle').val().replace(/\s+/g, '-').replace(/[^-A-Za-z0-9]+/g, '').toLowerCase());                       
        });
    });
    

    Fiddle