Reputation: 189
Suppose this is my text file info.txt :
My Name is
Joe
My Age is
25
My phone is
Nokia
Is there an efficient way to return 25 with Javascript (Knowing that it comes in the line after"My Age is" ?
I'm using vanilla Javascript and FileReader
Upvotes: 1
Views: 217
Reputation: 4452
txt.split(/Age.+/)[1].match(/.+/)
I would use .split()
as a cursor.
let txt =
`My Name is
Joe
My Age is
25
My phone is
Nokia`,
age = txt.split(/Age.+/)[1].match(/.+/)[0]
console.log(age)
Split the text content at the line that contains Age
and match the next line.
Upvotes: 1
Reputation: 32704
You can simply use RegEx for that:
let matches = str.match(/My Age Is\s?\n([0-9]+)/i)
let age = matches[1];
Here's the JSFiddle: https://jsfiddle.net/tee3y172/
And, here's how that breaks down:
([0-9]+)
- Followed by any series of numbers (you could also use \d+
) and group them (that's what the perenthesis are for).The grouping then allows you to capture the text you want at index 1 (matches[1]
).
For matching anything on the line after "My age is" you can use the (.*)
which will match anything except a newline:
let matches = str.match(/My Age Is\s?\n(.*)/i)
let age = (!!matches) ? matches[1] : 'No match';
Here's the JSFiddle for that: https://jsfiddle.net/spadLeqw/
Upvotes: 1
Reputation: 63524
The simplest method is to use a regular expression
to match the digits that come after specific words
const str = 'My Name is\nJoe\nMy Age is \n25\nMy phone is\nNokia';
const match = str.match(/My Age is \n(\d+)/)[1];
console.log(match);
Additional resources
Upvotes: 1