How do I split a string at a space after a certain number of characters in javascript?

17,573

Solution 1

Consider:

str = "How razorback-jumping frogs can level six piqued gymnasts!"
result = str.replace(/.{10}\S*\s+/g, "$&@").split(/\s+@/)

Result:

[
 "How razorback-jumping",
 "frogs can level",
 "six piqued",
 "gymnasts!"
]

Solution 2

.indexOf has a from parameter.

str.indexOf(" ", 10);

You can get the string before and after the split, respectively, with:

str.substring(0, str.indexOf(" ", 10));
str.substring(str.indexOf(" ", 10));

Solution 3

Is this what you are after? http://jsfiddle.net/alexflav23/j4kwL/

var s = "You is a dog and I am a cat.";
s = s.substring(10, s.length); // Cut out the first 10 characters.
s = s.substring(s.indexOf(" ") + 1, s.length); // look for the first space and return the
// remaining string starting with the index of the space.
alert(s);

To wrap it up, String.prototype.indexOf will return -1 if the string you are looking for is not found. To make sure you don't get erroneous results, check for that before the last part. Also, the index of the space may be string.length - 1(the last character in the string is a space), in which case s.index(" ") + 1 won't give you what you want.

Solution 4

This should do what you want, and no regexs

var string = "You is a dog and I am a cat.",
    length = string.length,
    step = 10,
    array = [],
    i = 0,
    j;

while (i < length) {
    j = string.indexOf(" ", i + step);
    if (j === -1) {
        j = length;
    }

    array.push(string.slice(i, j));
    i = j;
}

console.log(array);

On jsfiddle

And here is a jsperf comparing this answer and the regex answer that you chose.

Additional: if you want to trim the spaces from each block of text then change the code like so

array.push(string.slice(i, j).trim());

Solution 5

Here's a regex solution for some variety:

var result = [];
str.replace(/(.{10}\w+)\s(.+)/, function(_,a,b) { result.push(a,b); });

console.log(result); //=> ["You is a dog", "and I am a cat."]
Share:
17,573
muzzledBYbrass
Author by

muzzledBYbrass

Updated on June 22, 2022

Comments

  • muzzledBYbrass
    muzzledBYbrass almost 2 years

    So I have a nice long string that I need to split in Javascript at a space following a certain amount of characters. For instance, if I have

    "You is a dog and I am a cat."

    and I want it to split after 10 characters but at the next space... so rather than splitting dog up I want the next space to be the split point.

    I hope I wrote that clearly, its a bit awkward to explain.

    EDIT: I need to store all of this into an array. So splitting the string up as I described, but storing it into an array which I can iterate through. Sorry for the confusion- like I said, a bit odd to describe.

  • muzzledBYbrass
    muzzledBYbrass about 11 years
    nice, thank you sir. this is what I'm going for but I need to have an array of a much larger string. So if I have a 500 character string I want to have an array of the entire thing parsed like you have it here, but just applied to the entirety of the string.
  • Tim
    Tim about 11 years
    @elclanrs You is a clever fellow but you should document your code. :-)
  • muzzledBYbrass
    muzzledBYbrass about 11 years
    thanks for the response, but I need to store everything into an array, so I can't cut out anything. its gonna be a regex thing most likely.
  • elclanrs
    elclanrs about 11 years
    Knowing the requirements better now, this is what I would have done or similar but I usually prefer ~ rather than @ as token. Good stuff!
  • muzzledBYbrass
    muzzledBYbrass about 11 years
    the best answer- thank you. and to everyone for their responses
  • Xotic750
    Xotic750 about 11 years
    But what happened to the spaces? Are they not part of the text? I don't see anything in the questions that says to trim the spaces?
  • georg
    georg about 11 years
    @Xotic750: when we split a string by something, we're usually not interested in that "something". The question is essentially about wrapping a text - no need to preserve trailing spaces here.
  • Xotic750
    Xotic750 about 11 years
    I understand ´split´, but the OP also comments "but I need to store everything into an array, so I can't cut out anything.", to me that means lossless and I understand your assumption that it is not required. The problem is more to do with the unclear specification.
  • XaolingBao
    XaolingBao about 9 years
    Can someone explain what exactly is going on here? I looked up the first part and see it's a trim function, and seems to be using 10 as the trim amount but why is it .{10} and not {10}? What is the S* for? "$&@?" I tried looking up some of these with no help, so any advice would be appreciated.
  • georg
    georg about 9 years
    @Lasagna: that's regular expressions
  • XaolingBao
    XaolingBao about 9 years
    Thanks, I looked up the first part which seemed to be a sring trim, but I don't know waht the S* is for or the /\, I'll try to keep looking. I also see some of them like $& what's the @? Also is there a way to take what you did here, and use a variable x instead of 10? In my case the # is dependent on the size I am given. For example if I have a 60px width rect I will need 10 as my x. But if it's 30 I need 5 as my x.
  • georg
    georg about 9 years
    @Lasagna: "@" here is just an arbitrary character I use as a marker. It doesn't have any special meaning in regex. If you need "10" to be a variable, you have to use the RegExp constructor instead of a literal.
  • XaolingBao
    XaolingBao about 9 years
    So you can enter random characters and the regex will still work as intended? So you just use them for yourself gotcha. Thanks for this RegExp constructor, I will check it out, and hopefully it works :).
  • georg
    georg about 9 years
    @Lasagna: exactly, I could have used ~ or % with the same effect - the main thing, it shouldn't appear elsewhere in the text.
  • w3spi
    w3spi about 8 years
    Looking fot this for several hours. Excellent !
  • Philipp Schemel
    Philipp Schemel about 6 years
    Best answer. Thank you for saving my day!