Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace space ' ' by '-' on keyup

Hello i have two inputs and when im writing in the first input, with keyup jquery function im writing automatically in the second input field.

But I want to write line instead of space to the second input field when im clicking the spacebar.

For example:

First input: Hello world,

Second input: Hello-world

I have the following code:

$(".firstInput").keyup(function(e) {

    val = $(this).val();

    if( e.keyCode == 32 ) {
        val += "-";
    }

    $(".secondInput").val( val );
});
like image 305
Özkan Avatar asked Feb 13 '17 21:02

Özkan


People also ask

How do you replace a space in a string?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace a space with an underscore in react?

Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.


1 Answers

That could be done simply using replace, like :

$(".secondInput").val( $(this).val().replace(/ /g, "-") );

NOTE : I suggest the use of input instead of keyup since it's more efficient when you track the user input.

Hope this helps.

$(".firstInput").on('input', function(e) {
  $(".secondInput").val( $(this).val().replace(/ /g, "-") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class='firstInput' />
<input class='secondInput' />
like image 132
Zakaria Acharki Avatar answered Sep 22 '22 21:09

Zakaria Acharki