vNext vNext - 7 months ago 15
Javascript Question

get snippet text using javascript?

I have a long text. ex:

var text = "get snippet text using javascript?";


How can I write a method to get the snippet, not substring:

Ex: snippet(text,10) -> "get snippet..." not "get snippe" (10 characters). it means if the last character not a space or dot, we must get more characters until reach space or dot.

Any help?

Answer

Not tested thoroughly:

function getSnippet(text, length) {
    var rx = new RegExp("^.{" + length + "}[^ ]*");
    return rx.exec(text)[0];
}
console.log(getSnippet("get snippet text using javascript?", 1));  // get
console.log(getSnippet("get snippet text using javascript?", 3));  // get
console.log(getSnippet("get snippet text using javascript?", 10)); // get snippet
console.log(getSnippet("get snippet text using javascript?", 11)); // get snippet

You can add the ellipsis when the returned string is shorter than original string.