如何使用 javascript 拆分字符串 - 将名字和姓氏与文本框分开
我使用以下代码将姓氏与名字+中间名分开,并将它们放在三个单独的字段中。一个保存姓氏,一个保存名字,一个保存所有这些,但重新排列为姓氏,名字
function switchName(ele){
var splitName = ele.value.split(" ");
var surname = splitName[splitName.length-1]; //The last one
var firstnames
for (var i=0; i < splitName.length-1; i++){
firstnames += splitName[i] + " "
}
document.getElementById("hdnSNFNS").value = surname + ", " + firstnames;
document.getElementById("hdnEmployeeSurname").value = surname;
document.getElementById("hdnEmployeeFirst").value = firstnames;
它按原样工作,但我得到了名字的输出
石头,未定义乔斯·海伦
我已经使用它很长时间了,但无法偶然发现正确的解决方案。
I'm using the following code to split up surname from first + middle names and place them in three seperate fields. One holds the surname, one holds the firstnames and one holds all of them but re-arranged as lastname, firstname(s)
function switchName(ele){
var splitName = ele.value.split(" ");
var surname = splitName[splitName.length-1]; //The last one
var firstnames
for (var i=0; i < splitName.length-1; i++){
firstnames += splitName[i] + " "
}
document.getElementById("hdnSNFNS").value = surname + ", " + firstnames;
document.getElementById("hdnEmployeeSurname").value = surname;
document.getElementById("hdnEmployeeFirst").value = firstnames;
It works as is but I get this output for the firstnames
Stone, undefinedJoss Helen
I've played around with it for ages but cant stumble across the correct solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第 4 行缺少
;
,您应该将firstnames
初始化为空字符串。var 名字 = "";
。现在,循环的第一次迭代将第一个名称连接到一个未初始化的变量,这就是
undefined
的来源。通过初始化,您将与“nothing”连接,它将产生预期的结果。You're missing a
;
on the 4th line line and you should initializefirstnames
to an empty string.var firstnames = "";
.Right now, the first iteration of your loop concatenates the first name to an uninitialized variable and that's where the
undefined
comes from. With the initialization you'll concatenate with "nothing" and it will produce the expected result.