JavaScript – How to Replace All Spaces in a String

javascriptjqueryreplacestring

I have two html text input, out of that what ever user type in first text box that need to reflect on second text box while reflecting it should replace all spaces to semicolon. I did to some extant and it replacing for first space not for all, I think I need to use .each function of Jquery, I have used .each function but I didn't get the result see this

HTML :

Title : <input type="text" id="title"><br/>
Keyword : <input type="text" id="keyword">

Jquery:

$('#title').keyup(function() {
    var replaceSpace = $(this).val(); 

        var result = replaceSpace.replace(" ", ";");

        $("#keyword").val(result);

});

Thanks.

Best Answer

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

Related Question