string.Slice() returns empty string

Asked

Viewed 31 times

-1

I’m trying to make a system of putting words together, and I thought I’d use the .slice(). But it returns an empty string. I have already searched but no one has explained it properly. I have two text inputs, and I want to make the first one lose the second half and the second one lose the first half. This is the code that returns an empty string:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="text" id="name1"><input type="text" id="name2"><br>
  <input type="button" value="Juntar" onclick="juntar()"><br>
  <script>
    var name1 = document.getElementById('name1').value;
    var name2 = document.getElementById('name2').value;

    function juntar() {
      var name1slice = `${name1.slice(0, name1.length / 2)}`
      var name2slice = `${name2.slice(name2.length / 2, name2.length)}`
      var slice12 = `${name1slice}${name2slice}`
      alert(`${slice12}`)
    }
  </script>
</body>

</html>

  • 1

    Only one detail, do not need to use template string in these cases, could do only var name1slice = name1.slice(0, name1.length / 2) and alert(slice12), for example. Even to concatenate, it could be slice12 = name1slice + name2slice

  • I didn’t know that, I thought if I did slice12 = name1slice + name2slice the return would be Nan

  • 1

    Like name1slice and name2slice are strings (because slice returns a string), the operator + concatenate. NaN appears when you try to do mathematical operations with strings that do not represent numbers, etc. But in this case you are only manipulating strings, so you can concatenate without problem

  • ok thanks for the help!

1 answer

0


Next, what is happening is that your script runs when the DOM is generated, so the values of the fields are empty. To solve your problem of having the string return empty, just declare the variables within the function, so the values already exist.

Your script would look like this:

 <script>
        function juntar() {
            var name1slice = `${name1.slice(0, name1.length / 2)}`
            var name2slice = `${name2.slice(name2.length / 2, name2.length)}`
            var slice12 = `${name1slice}${name2slice}`
            var name1 = document.getElementById('name1').value;
            var name2 = document.getElementById('name2').value;
            alert(`${slice12}`)
        }
 </script>

If the result is not yet as expected, the error will be in the logic used in slice()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.