简体   繁体   English

Javascript在第一个空格处分割字符串

[英]Javascript Split String on First Space

I have the following code as part of a table sorting script. 我将以下代码作为表排序脚本的一部分。 As it is now, it allows names in the "FIRST LAST" format to be sorted on LAST name by "reformatting" to "LAST, FIRST". 现在,它允许通过“重新格式化”为“ LAST,FIRST”将“ FIRST LAST”格式的名称按LAST名称排序。

var FullName = fdTableSort.sortText;
function FullNamePrepareData(td, innerText) {
  var a = td.getElementsByTagName('A')[0].innerHTML;
  var s = innerText.split(' ');
  var r = '';
  for (var i = s.length; i > 0; i--) {
    r += s[i - 1] + ', ';
  }
  return r;
}

It currently seems to sort on the name after the LAST space (ex. Jean-Claude Van Damme would sort on 'D'). 目前,它似乎是按LAST空格的名称排序(例如Jean-Claude Van Damme将按'D'排序)。

How could I change this script to sort on the FIRST space (so Van Damme shows up in the V's)? 我该如何更改此脚本以在FIRST空间排序(以便Van Damme出现在V形空间中)?

Thanks in advance! 提前致谢!

You can shorten that functio a bit by the use of array methods : 您可以通过使用数组方法来稍微缩短该功能:

function FullNamePrepareData(td, innerText) {
    return innerText.split(' ').reverse().join(', ');
}

To put only the first name behind everything else, you might use 要仅在其他所有内容后面加上名字,可以使用

function FullNamePrepareData(td, innerText) {
    var names = innerText.split(' '),
        first = names.shift();
    return names.join(' ')+', '+first;
}

or use a Regexp replace : 或使用Regexp替换

function FullNamePrepareData(td, innerText) {
    return innerText.replace(/^(\S+)\s+([\S\s]+)/, "$2, $1");
}

Instead of the .split() and the loop you could do a replace: 代替.split()和循环,您可以执行替换操作:

return innerText.replace(/^([^\s]+)\s(.+)$/,"$2, $1");

That is, find all the characters up to the first space with ([^\\s]+) and swap it with the characters after the first space (.+) , inserting a comma at the same time. 也就是说,使用([^\\s]+)查找到第一个空格为止的所有字符,并将其与第一个空格(.+)之后的字符交换,同时插入一个逗号。

I don't know where the sorting happens; 我不知道分类发生在哪里; it sounds like you just want to change the reordering output. 听起来您只是想更改重新排序输出。

The simplest would be to use a regexp: 最简单的是使用regexp:

// a part without spaces, a space, and the rest
var regexp = /^([^ ]+) (.*)$/;

// swap and insert a comma
"Jean-Claude Van Damme".replace(regexp, "$2, $1"); // "Van Damme, Jean-Claude"

I think you're after this: 我认为您是在追求:

    var words = innerText.split(' '),
        firstName = words.shift(),
        lastName = words.join(' ');
    return lastName + ', ' + firstName;        

Which would give you "Van Damme, Jean-Claude" 那会给你“范·达姆,让-克洛德”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM