Eddie Costa Domingues Eddie Costa Domingues - 7 months ago 11
Javascript Question

How do you get some value in the the middle of userInput

For example, I just want to get the ID which is at the end How do I do that?



<html>
<head>
<script>
function ()
}
var userInput = document.getElementById("1").value;
window.alert("Your id is " + userInput
{
</script>
</head>
<body>
<input id="1" type="text" value="my id is 1743876">
</body>
<html>




Answer

document.getElementById("1").value.split(' ').pop(); should do it.

split(' ') breaks a string up into an array of strings using the delimiter you pass it (in this case a space: ' ').

pop() returns the last element of an array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

As Gary said, for more complex needs, you should use a regular expression function like match().

var matches = document.getElementById("1").value.match(/(\d+)/);
matches[0]; // contains the match

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Comments