将字符串拆分为3个子串jquery / javascript [英] Splitting a string into 3 substrings jquery/javascript

查看:88
本文介绍了将字符串拆分为3个子串jquery / javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,我在其中写下员工的全名。我想检索第一个单词作为名字,最后一个单词作为姓氏,剩下的中间字符串作为中间名。例如。 for

I have a text field in which I write the full name of the employee. I want to retrieve the first word as first name, last word as last name and the remaining middle string as middle name. For eg. for

ramesh suresh mahesh roshan

名字应为 ramesh ,中间名为 suresh mahesh ,姓氏为 roshan

the first name should be ramesh, middle name as suresh mahesh and last name as roshan.

有没有办法用jquery / javascript做到这一点?请帮忙!

Is there any way to do this using jquery/javascript? Please help!

推荐答案

这是一种方法


  1. 使用 string.split() ,根据空格拆分字符串。

然后通常,


  1. 0 指数 - 代表名字

  2. (last - 1) th index - 代表姓氏

  3. 所以对于中间名我是迭代剩余的索引和
    连接
    彼此。

  1. 0th index - represents first name
  2. (last - 1)th index - represents the last name
  3. So for middle name I'm iterating the remaining index and concatenating each other.







var name = "ramesh suresh mahesh roshan";
var d = name.split(" ")

console.log("first Name : " + d[0]);
console.log("Last Name : " + d.length != 1 ? d[d.length -1] : "");
var mid = "";
for (var i = 1; i <= d.length - 2; i++) {
    mid = mid + " " +  d[i];
}
console.log("middle name: " +mid);

JSFiddle

这篇关于将字符串拆分为3个子串jquery / javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆