Replace the space '' with '-' on the keyboard

Hello, I have two inputs and when im write on the first input, with the jquery keyup im function that automatically writes in the second input field.

But I want to write a line instead of a space in the second input field when im presses a space.

For instance:

First entry: Hello world,

Second Entry: Hello-world

I have the following code:

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

    val = $(this).val();

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

    $(".secondInput").val( val );
});
+4
source share
3 answers

This can be done simply with replace, for example:

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

NOTE. I suggest using inputinstead keyup, as it is more efficient at tracking 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' />
Run codeHide result
+5

- .. , , . , :

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

    //grab the text, note the use of the var keyword to prevent messing with the global scope
    var input1 = $(this).val();

    // break the string into an array by splitting on the ' '. Then join the array into a string again with '-' as the glue
    input1 = input1.split(' ').join('-');

    // or use regex, but regex is a whole other language:  input1 = input1.replace(/ /g, "-") 

    //finally place the modified string into its destination 
    $(".secondInput").val( input1 );
});
+1

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

    val = $(this).val();
    val = val.replace(/\s/g, '-');

    $(".secondInput").val( val );
});
Run codeHide result
0
source

Source: https://habr.com/ru/post/1669635/


All Articles