2016-04-30 91 views
1

例如,我只想获得最终的ID,我该怎么做?如何在用户输入中获得一些价值输入

<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>

+0

该值是否始终为该格式?如果是这样,分割将工作。否则,正则表达式可能是要走的路。 – Gary

回答

1

document.getElementById("1").value.split(' ').pop();应该这样做。

split(' ')使用您传递给它的分隔符将字符串分解为一个字符串数组(在本例中为空格:' ')。

pop()返回数组的最后一个元素。

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

正如Gary说,对于更复杂的需求,您应该使用正则表达式的功能就像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

0

从字符串值中提取ID,你应该使用正则表达式。

在这种情况下,你知道的号码/数字的ID的确切量可以使用正则表达式像这样的/\b\d{11}\b/g

var userInput = document.getElementById("1").value.match(/\b\d{11}\b/g); 

在这种情况下,你知道ID会变化和11之间的9位数字你可以使用正则表达式像这样的/\b\d{9,11}\b/g

var userInput = document.getElementById("1").value.match(/\b\d{9,11}\b/g); 

所以也没有身在何处的ID所对应的字符串中,你总是会得到它。

+0

thx也有帮助 –