RegExp to read txt and filter and only read first match

Home / Uncategorized / RegExp to read txt and filter and only read first match

Question:
I’m reading a txt file that has multiple lines like below.

lastname australia enter

name j.jonhs enter

name j.cause enter

name f.london enter

I’d like to use regexp to read the first line that matches name only and stop reading, can someone help me modify the line below?
output=output.split("n").filter(/./.test, /name/).join("n").replace("name", "").replace("enter", "");


Answer:
after spiting you got an array. Why don’t just target index 0 as-
output=output
.split("n")[0]
.replace("name", "")
.replace("enter", "");
edit after question modification

as you have specific matching on name, you can use substring as-
const s = `lastname australia enter

name j.jonhs enter

name j.cause enter

name f.london enter`;

let ns = s.split("n").find((item) => item.substring(0, 4) === ‘name’)
if(ns){
// found do something here.
}else{
// not found
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *