-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>
Only one detail, do not need to use template string in these cases, could do only
var name1slice = name1.slice(0, name1.length / 2)
andalert(slice12)
, for example. Even to concatenate, it could beslice12 = name1slice + name2slice
– hkotsubo
I didn’t know that, I thought if I did
slice12 = name1slice + name2slice
the return would be Nan– user225490
Like
name1slice
andname2slice
are strings (becauseslice
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– hkotsubo
ok thanks for the help!
– user225490