按字符数计取字符串的特定部分

时间:2015-11-17 14:36:26

标签: javascript string split

我想获取用户提交的字符串并将其中的一部分用作不同的变量。 我用它来分解每三个字母后的文字......

var values = value.match(/.{3}|.{1,2}/g);

这给了我一个很好的字符串数组,分为3:

["658", "856", "878", "768", "677", "896"]

然而我意识到这不是我需要的。我实际上需要前2个字母(var 1),接下来的3个字母(var 2),接下来的1个字母(var 3)等等。

所以我基本上会把它们拆分得更像......

["65", "885", "6" .....

我真的不需要一个数组,因为它每次都会是一个长数字,它看起来更像......

var Part1 = Number.(grab first 2 characters)
var Part2 = Number.(grab 3 characters from the 3rd onwards)
var Part3 = Number.(grab 6th character only)

等等。如果你可以想象那些正确编码。我无法找到.match方法的详细信息。

4 个答案:

答案 0 :(得分:2)

您可以使用.substr()代替match()

// grab first 2 characters
"123456789".substr(0, 2);  //return "12"

// grab 3 characters from the 3rd onwards
"123456789".substr(2, 3);  //return "345"

// grab 6th character only
"123456789".substr(5, 1);  //return "6"

希望这有帮助。

答案 1 :(得分:1)

我希望这就是你要求的

myDirective

这是输出:

var value = "123456789123456789";
var values = [];
while(value.length){
    [2, 3, 1].forEach(function(d){
        values.push(value.substr(0,d));
        value = value.substr(d);
    })
}

values = ["12", "345", "6", "78", "912", "3", "45", "678", "9"] 字符串在循环结束时将为value,因此如果您想重复使用它,请复制它。

答案 2 :(得分:0)

正如上面的@Teemu建议的那样,您可以使用substr()substring()字符串方法。

例如:

var Part1 = value.substr(0, 2);
var Part2 = value.substr(2, 3);
var Part3 = value.substr(5, 1);

请参阅此处的JS小提琴示例:https://jsfiddle.net/xpuv4e5j/

答案 3 :(得分:0)

Actually, you can use a regular expression to extract multiple substrings in a single call the the match function. You just need to add parenthesis to your regular expression, like this:

var s = "1234567890";
var s.match(/([0-9]{3})([0-9]{1})([0-9]{2})([0-9]{3})/);
for( var i=0; i<matches.length; ++i ) {
    console.log(matches[i]);
}

Output:

123456789
123
4
56
789

Notice that match returns the entire match as element zero of the returned array. My example regex only extracts nine characters, so that's why there is no zero in the output.

IMHO Regular expressions are worth learning because they give you a powerful and concise way to perform string matching. They work (mostly) the same from one language to another, so you can apply the same knowledge in JavaScript, python, ruby, java, whatever.

For more information about regular expressions in JavaScript, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions