Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - how to break up a string every X amount of characters?

Tags:

javascript

How do I break up a string every X amount of characters? For example, I'd like to break up a very long string every 1000 characters, and the string could be completely random everytime.

var string = <my text string that is thousands of characters long>

like image 874
James Nine Avatar asked Mar 13 '12 20:03

James Nine


People also ask

How do you split a string with every nth character?

To split a string every n characters: Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.

How do you half a string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string into values?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

How do you split a string into characters?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

You could use Regex:

'asdfasdfasdfasdf'.match(/.{3}|.{1,2}/g); // 'asd', 'fas', etc.

Replace 3 with 1000 of course.

Here's a contrived example: http://jsfiddle.net/ReRPz/1/


As a function:
function splitInto(str, len) {
    var regex = new RegExp('.{' + len + '}|.{1,' + Number(len-1) + '}', 'g');
    return str.match(regex );
}

That RegExp really only needs to be created once if you have a set number to split like 1000.

like image 168
Joe Avatar answered Oct 19 '22 23:10

Joe


Try this function:

function getParts(str, len)
{
    var res = [];
    ​while (str.length) {
        res.push(str.substring(0, len));
        str = str.substring(len);
    }
    return res;
}
var s = "qweasedzxcqweasdxzc12";
console.log(getParts(s, 10));

like image 26
Just_Mad Avatar answered Oct 20 '22 01:10

Just_Mad