简体   繁体   English

如何在javascript中将一个字符串拆分为两个字符串?

[英]how to split a string in two strings in javascript?

I have a string with a lot of characters.我有一个包含很多字符的string I would like to split the string into 2 sub-strings.我想将string拆分为 2 个子字符串。 I don't need to use getfirsthalf() and getsecondhalf() , but that is the idea of what i need to achieve.我不需要使用getfirsthalf()getsecondhalf() ,但这就是我需要实现的想法。

var compleet = "This is the string with a lot of characters";

var part1 = compleet.getFirstHalf();
var part2 = compleet.getSecondHalf()

//output 
var part1 = "This is the string wi";
var part2 = "th a lot of characters";

You can use substring() with the length of the string to divide the string in two parts by using the index.您可以使用带有字符串lengthsubstring()使用索引将字符串分成两部分。

The substring() method returns a subset of a string between one index and another, or through the end of the string. substring() 方法返回一个索引和另一个索引之间或通过字符串末尾的字符串子集。

 var compleet = "This is the string with a lot of characters"; var len = compleet.length; var firstHalf = compleet.substring(0, len / 2); var secondHalf = compleet.substring(len / 2); document.write(firstHalf); document.write('<br />'); document.write(secondHalf);

You can also use substr()您也可以使用substr()

You must to be more specific in your questions.你的问题必须更具体。 But here you are a simply solution:但这里有一个简单的解决方案:

var str = "an string so long with the characters you need";
var strLength = str.length;
console.log(str.substring(0 , (strLength / 2));
console.log(str.substring((strLength / 2));

Assuming that when you say 'half' a string, you actually mean that two separate strings are returned containing half of the original string's characters each, you could write a prototype function to handle that as follows:假设当您说“一半”字符串时,实际上是指返回两个单独的字符串,每个字符串都包含原始字符串字符的一半,您可以编写一个原型函数来处理如下:

String.prototype.splitInHalf = function()
{
    var len = this.length,
        first = Math.ceil( len / 2 );

    return [
        this.substring(0, first),
        this.substring(first)
    ];
}

When called as compleet.splitInHalf() , This function will return an array containing the two halves, as follows:当作为compleet.splitInHalf()调用时,此函数将返回一个包含两半的数组,如下所示:

["This is the string wit", "h a lot of characters"]

Since we use Math.ceil() here, the prototype will also favour the first half of the string.由于我们在这里使用Math.ceil() ,因此原型也将偏爱字符串的前半部分。 For example, given a string that has an odd number of characters, such as This is , the returned array will contain 4 characters in the first string, and 3 in the second, as follows:例如,给定一个包含奇数个字符的字符串,例如This is ,返回的数组将在第一个字符串中包含 4 个字符,在第二个字符串中包含 3 个字符,如下所示:

["This", " is"]

jsFiddle Demo jsFiddle 演示

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

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