简体   繁体   中英

how to split a string in two strings in javascript?

I have a string with a lot of characters. I would like to split the string into 2 sub-strings. I don't need to use getfirsthalf() and getsecondhalf() , but that is the idea of what i need to achieve.

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.

The substring() method returns a subset of a string between one index and another, or through the end of the string.

 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()

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:

["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. 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"]

jsFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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