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
JavaScript
x
10
10
1
"111"1"13648""
2
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
3
"101"1"00000368""
4
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
5
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
6
""
7
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
8
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
9
3646475
10
Would turn into this:
JavaScript
1
4
1
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
2
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
3
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
4
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
JavaScript
1
2
1
str.split('n').filter(d => d.indexOf(':tesTWORD:') > -1).join('n')
2
JavaScript
1
13
13
1
let str = `"111"1"13648""
2
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
3
"101"1"00000368""
4
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
5
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
6
""
7
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
8
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
9
3646475`
10
11
let result = str.split('n').filter(d => d.indexOf(':tesTWORD:') > -1).join('n')
12
13
console.log(result)