tam tam
tam tam

Reputation: 1900

Remove characters from string with Javascript

I have a string in the following format. Im trying to create a function in Java Script to remove certain charcters.

Sample String:

Var s = '18160 ~ SCC-Hard Drive ~ 4 ~ d | 18170 ~ SCC-SSD ~ 4 ~ de | 18180 ~ SCC-Monitor ~ 5 ~ | 18190 ~ SCC-Keyboard ~ null ~'

Desired Result:

s = 'SCC-Hard Drive ~ 4 ~ d | SCC-SSD ~ 4 ~ de | SCC-Monitor ~ 5 ~ |SCC-Keyboard ~ null ~'

If you notice above the ID'S for instance 18160, 18170, 18180 and 18190 were removed. This is just as example. the structure is as follows:

id: 18160
description : SCC-Hard Drive
Type: 4
comment: d

So where there are multiple items they get concatenated using the Pike delimeter. So my requirement is to remove the id's from a given string in the above structure.

Upvotes: 1

Views: 109

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

I'll use the replace function with following regex since number of digits in the ID field can vary.

s.replace(/(^|\|\s)\d+\s~\s/g, '$1')

Upvotes: 1

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

Using the string.replace() method perhaps.

s.replace(/\d{5}\s~\s/g, "")

\d{5} - matches 5 digits (the id)
\s    - matches a single space character
~     - matches the ~ literally

Output:

"SCC-Hard Drive ~ 4 ~ d | SCC-SSD ~ 4 ~ de | SCC-Monitor ~ 5 ~ | SCC-Keyboard ~ null ~"

Also, note that Var isn't valid. It should be var.

Upvotes: 3

Related Questions