Munir Abrar
Munir Abrar

Reputation: 81

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.

Upvotes: 0

Views: 507

Answers (2)

rfornal
rfornal

Reputation: 5122

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/

Upvotes: 1

Kaiido
Kaiido

Reputation: 136986

If I understand well your requirements, you could use this regex.
(maybe not the most powerful, I'm not a regex specialist at all)

/^(\s\bby\b|\bby\b).*$/gmi
  • Little walkthrough starting by last modifiers :
     g global, it won't return at first occurence.
     m multiline, ^ and $ will match start/end of line, instead of string
     i insensitive, I bet you got it
  • Now, back to the beginning.
     ^ will search at start of the string
     (x|y) is a capturing group with two alternatives (x or y)
     \s\ is any white-space (\r\n\t\f)
     \bword\b is a word boundary, e.g it won't catch "words"
     .* matches any character (except newline), until
     $ end of string/line here

//those should be found
var text = "by test 1 \n" +
  " by test 2 \n" +
  "By test 3 \n" +
  " By test 4 \n" +

  //Those should not
  "test By 5 \n" +
  "test by 6 \n" +
  "Bya test 7 \n" +
  "bya test 8 \n" +
  " Bya test 9 \n" +
  " bya test 10 \n";

var matchingLines = text.match(/^(\s\bby\b|\bby\b).*$/gmi);

document.querySelector('p').textContent = "|" + matchingLines.join("|") + "|";
<p/>

Upvotes: 0

Related Questions