Search code examples
javascriptregexstringpug

Split a string in two, keeping words intact and returning them


As the title says, looking to see how I can split a string into two parts, while keeping full words intact, and having access to both parts with JavaScript. I am using this string in a pug file.

For instance, I have a very long string

let str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.'

I want the first 70 characters, to use as a headline, then the rest to use for the body of the element.

I have used this regex that I found on an older post that gives me the first 70+ characters, with full words...

str.replace(/^([\s\S]{70}[^\s]*)[\s\S]*/, "$1")

which does what I want it to do! But now I need to figure out if there is a way to get the rest of that string?

str1 = `hello i am a very long string that needs to be split into two different`
str2 = `parts! thank you so much for helping.`

Again, using this in a pug file, so if there is a simple answer, I would love that. Otherwise I suppose I could just write a function and import the script to the pug view.


Solution

  • After extracting the first part of the string using your method you can use the length of str1 to determine where in str the second part begins. From there you can use substring to extract it.

    let str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.`;
    let str1 = str.replace(/^([\s\S]{70}[^\s]*)[\s\S]*/, "$1");
    let str2 = str.substring(str1.length).trimStart();
    

    Using trimStart you can to remove any whitespace that would appear at the start of str2.