Search code examples
javascriptstartswith

Javascript — Find And Cut if StartsWith


I need to see if the first line of text starts with a By and if true, cut the whole line and store it in a variable and remove all blank lines until the next paragraph starts. The method to find By needs to be case insensitive and it may have some preceding white spaces too. And do nothing if the first line isn't starting with a By.

var findBy = 'By Bob';
if (findBy.startsWith('By ')) {
findBy = copyBy;
findBy.split("\n").slice(1).join("\n");
}
var pasteBy = copyBy; 

Let me rephrase myself: Find if first line starts with By If it does, save the entire line containing By in a variable then delete it.


Solution

  • Adjustment ...

    function removeBy(textArray) {
      var capture = false;
      rebuild = [];
      for (var i=0,len=textArray.length; i<len; i++) {
        var s = textArray[i].trim();
        if (s.substring(0,3).toUpperCase()==="BY ") {
          capture = true;
        } else if (capture && s!=="") {
          capture = false;
        }
    
        if (capture) {
          rebuild.push(s);
        }
      }
      return rebuild;
    }
    

    This function assumes you are sending an array of strings and returns a stripped array.

    var answer = removeBy(["By Bob", "", "", "This is the result"]);
    // answer = ["By Bob"];
    

    Fiddle: http://jsfiddle.net/rfornal/ojL72L8b/

    If the incoming data is separated by line-breaks, you can use the .strip() function to make the textArray; In reverse, the rebuild returned can be put back together with answer.join("\n");

    UPDATE

    Based on comments, changed substring to (0,3) and compared against "BY " (space) to ONLY watch for BY not something like BYA.

    Updated Fiddle: http://jsfiddle.net/rfornal/b5gvk48c/1/