Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you delete every line inside of a string that doesn't contain a specific word?

There’s a string with multiple lines of random characters, I’d like to delete every line that doesn’t contain the word

:tesTWORD:

For example, this part of the original string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475

Would turn into this:

PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b

So basically all lines that don’t contain the exact word :tesTWORD: get deleted.

I have tried a bunch of different things like playing around with arrays, but nothing worked like it’s supposed to

>Solution :

You can use \n to split it into an array,then filter the array,finally using join() to form a new string

str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')
let str = `"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475`

let result = str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading