javascript - What's the best way to seperate the first line of a string from the rest in JS? -


in python, there old firstline, rest = text.split("\n", 1). after painful discovery, realized javascript gives different meaning limit property, , returns many "splits" (1 means returns first line, 2 returns first 2 lines, , forth).

what's best way wanted? have make slice , indexof?

probably efficient way:

function getfirstline(text) {     var index = text.indexof("\n");     if (index === -1) index = undefined;     return text.substring(0, index); } 

then:

// "some string goes here" console.log(getfirstline("some string goes here\nsome more string\nand more\n\nmore")); // "asdfasdfasdf" console.log(getfirstline("asdfasdfasdf")); 

edit:

function newsplit(text, linesplit) {     if (linesplit <= 0) return null;      var index = -1;     (var = 0; < linesplit; i++) {         index = text.indexof("\n", index) + 1;         if (index === 0) return null;     }      return { 0: text.substring(0, index - 1), 1: text.substring(index) } } 

output:

newsplit("someline\nasdfasdf\ntest", 1);     > object {0: "someline", 1: "asdfasdf↵test"} newsplit("someline\nasdfasdf\ntest", 2);     > object {0: "someline↵asdfasdf", 1: "test"} newsplit("someline\nasdfasdf\ntest", 0);     > null newsplit("someline\nasdfasdf\ntest", 3);     > null 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -