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
"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
Advertisement
Answer
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)