简体   繁体   English

如何使用Javascript将两部分填充的字符串拆分为两个变量?

[英]How can I split a two part padded string into two variables with Javascript?

I have a string, userName , that looks something like this: 我有一个字符串userName ,看起来像这样:

var userName = "CityOfLiverpool-----joesmith";
var userName = "Hull----------------janesmith";

The first part of userName is the Account: "CityOfLiverpool" userName的第一部分是帐户: "CityOfLiverpool"

The second part of userName is the User: "joesmith" userName的第二部分是用户: "joesmith"

The Account is always a maximum of 20 characters and is padded to the right with hyphens. 帐户最多为20个字符,并用连字符填充到右侧。

How can I extract the Account and the User? 如何提取帐户和用户?

Use a regexp with capture groups for the two parts that are separated by hyphens. 对于由连字符分隔的两个部分,请使用带有捕获组的正则表达式。

var match = userName.match(/^([^-]+)-+(.*)$/);
var firstName = match[1];
var lastName = match[2];

A simple way: 一个简单的方法:

var parts = userName.split('-');
var firstPart = parts[0];
var lastPart = parts[parts.length - 1];

You can extract the Account and User with a regular expression : 您可以使用正则表达式提取帐户和用户:

userName.match(/^([^-]{1,20})-*(.*)$/)

The ^ matches the start of the string and $ matches the end. ^匹配字符串的开头, $匹配结束。 [^-] matches any character that is not a hyphen, and [^-]{1,20} matches anywhere between 1 and 20 such characters. [^-]匹配任何不是连字符的字符, [^-]{1,20}匹配1到20个这样的字符。 -* matches zero or more hyphens. -*匹配零个或多个连字符。 .* matches zero or more characters of any kind. .*匹配任何类型的零个或多个字符。

The whole regular expression breaks down as follows: 整个正则表达式分解如下:

^             start of string
([^-]{1,20})  1 to 20 characters, each of which is not a hyphen
-*            zero or more hyphens
(.*)          zero or more characters of any kind
$             end of string

After doing 做完之后

match = userName.match(/^([^-]{1,20})-*(.*)$/)

you can look up the first parenthesized group as match[1] and the second parenthesized group as match[2] . 您可以将第一个带括号的组查找为match[1] ,将第二个带括号的组查找为match[2]

 var userName = "Hull----------------janesmith"; var match = userName.match(/^([^-]{1,20})-*(.*)$/), account = match[1], user = match[2]; document.write('account = "'+account+'"<br />user = "'+user+'"'); 

Some of this solutions will not work if the user name contains hyphens or if the account is 20 characters long. 如果用户名包含连字符或帐户长度为20个字符,则某些解决方案将无法使用。 This is an alternative based on the fact that the account is always 20 characters: 这是一个基于帐户总是20个字符的替代方案:

var account = userName.substr(0,20).replace(/-+$/, "");
var name = userName.substr(20, userName.length-20);

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

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