0

So what if instead of doing:

if (apple == red) {
alert ("red")

i would do:

The apple is red

if (line 1 == red) {
alert ("red")

so my question is if it is possible to make a statement with a line number instead of actual syntax in Javascript.

hello12345
  • 17
  • 2

2 Answers2

2

Assuming you're talking about a string (text) you have separated by a new line character.

var lines = text.split('\n');
if(lines.length) {
    if(lines[0].match(/red/)) {
        alert("The first line is red");
    }
}

http://jsfiddle.net/fa6e4xyk/

Ryan
  • 14,392
  • 8
  • 62
  • 102
0

Confusing but two solutions:

.split()

var lines = myText.split('\n'); //Splits lines
if (lines[0].toLowerCase().indexOf('red') > -1) { // Checks if 0th (1st line) contains 'red'
    alert("Red!");
}

Read text after is

var noun = 'apple',
    lines = myText.split('\n');

if (lines[0].match(new RegExp(noun+'\s*is\s*\b(\w+?)\b', 'i'))[1] === 'red') {
   alert('Red!');
}

Basic answer

You can split a text into lines using: .split('\n'). Example

var lines = multiLineTextString.split('\n');

Now in JavaScript, lines will start at zero so the first line will be 0 the second 1, etc. So to select it:

line[0] === 'red'

This will be true if the text of the first line is red

Downgoat
  • 13,771
  • 5
  • 46
  • 69