如何使用 javascript 拆分字符串 - 将名字和姓氏与文本框分开

发布于 2024-11-06 09:45:28 字数 712 浏览 1 评论 0原文

我使用以下代码将姓氏与名字+中间名分开,并将它们放在三个单独的字段中。一个保存姓氏,一个保存名字,一个保存所有这些,但重新排列为姓氏,名字

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十级心震 2024-11-13 09:45:28

第 4 行缺少 ;,您应该将 firstnames 初始化为空字符串。

var 名字 = "";

现在,循环的第一次迭代将第一个名称连接到一个未初始化的变量,这就是 undefined 的来源。通过初始化,您将与“nothing”连接,它将产生预期的结果。

You're missing a ; on the 4th line line and you should initialize firstnames 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.

南城追梦 2024-11-13 09:45:28
function switchName(ele){
    var splitName = ele.value.split(" ");
    var surname = splitName[splitName.length-1]; //The last one
    var firstnames = ""; // <- forgot to initialize to an empty string
    for (var i=0; i < splitName.length-1; i++){
        firstnames += splitName[i] + " "
    }
}
function switchName(ele){
    var splitName = ele.value.split(" ");
    var surname = splitName[splitName.length-1]; //The last one
    var firstnames = ""; // <- forgot to initialize to an empty string
    for (var i=0; i < splitName.length-1; i++){
        firstnames += splitName[i] + " "
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文