[英]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.
我试图在Java脚本中创建一个函数来删除某些字符。
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. 如果你注意到上面的ID'S例如18160,18170,18180和18190被删除了。 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.
所以我的要求是从上面结构中的给定字符串中删除id。
Using the string.replace()
method perhaps. 也许使用
string.replace()
方法。
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. 另请注意,
Var
无效。 It should be var
. 它应该是
var
。
我将使用以下正则表达式的替换函数,因为ID字段中的位数可以变化。
s.replace(/(^|\|\s)\d+\s~\s/g, '$1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.