-2

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";
3
  • what effort have you made? Jul 31, 2015 at 11:04
  • 1
    What defines 'half' of a string?
    – BenM
    Jul 31, 2015 at 11:04
  • @DontVoteMeDown What if the string has 7 characters?
    – BenM
    Jul 31, 2015 at 11:10

3 Answers 3

4

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

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.