简体   繁体   English

是否可以删除某个字符留下的整个字符串

[英]Is it possible to remove a whole string that is left from a certain character

I am going through values of strings and i compare them to a value i get from a grid.我正在检查字符串的值,并将它们与从网格中获得的值进行比较。 But the text i get has a lot of unwanted characters before the actual useful one.但是我得到的文本在实际有用的字符之前有很多不需要的字符。 But they all end with a html tag, so what im trying to do is cut the value i get from that tag.但是它们都以 html 标签结尾,所以我想要做的是削减我从该标签获得的价值。

Here is an example of the stuff i get in the string:这是我在字符串中得到的东西的一个例子:

<i class="icon status red"></i>, 1 - deleted

and what i want the string to be:我希望字符串是什么:

1 - deleted

So far i have tried this:到目前为止,我已经尝试过:

data.forEach((value: any) =>{
((this.array.find(x => x.value === value['field'])).text).split("</i>")
});

Which just removes the tag but i still get the rest of the text.这只是删除了标签,但我仍然得到文本的 rest。 I am looking for a short solution and not something like this:我正在寻找一个简短的解决方案,而不是这样的:

list = ["foo","bar","foobar"]

index = list.index("bar")

a = list[index - 1]

b = list[index + 1]

print(a, b)

Since i want to cut directly from string and not a list.因为我想直接从字符串而不是列表中剪切。 So what i was thinking is that i would just remove everything thats right from.所以我在想的是我会删除所有正确的东西。 Is it possible?可能吗?

Why would you run forEach loop.为什么要运行 forEach 循环。 with slice and split, you can have the string like you want, here you go:使用切片和拆分,您可以拥有想要的字符串,这里是 go:

 let string = "<i class='icon status red'></i>, 1 - deleted" let list = string.split(",") console.log(list[1])

One could utilize DOMParser and DOMParser.parseFromString in order to access just text content...可以利用DOMParserDOMParser.parseFromString来访问文本内容...

 function getTextContentFromMarkup(markup) { return new DOMParser().parseFromString(markup, "text/html").body.textContent; } console.log( `getTextContentFromMarkup('<i class="icon status red"></i>, 1 - deleted')... "${ getTextContentFromMarkup('<i class="icon status red"></i>, 1 - deleted')}"` );

The above script could be easily adapted to a more robust approach which returns just the value of the last text node...上面的脚本可以很容易地适应一种更强大的方法,它只返回最后一个文本节点的值......

 function getLastTextNodeValueFromMarkup(markup) { return [...new DOMParser().parseFromString(markup, "text/html").body.childNodes ].filter(node => node.nodeType === 3).at(-1)?.nodeValue; } console.log( `getLastTextNodeValueFromMarkup('<i class="icon status red"></i>, 1 - deleted')... "${ getLastTextNodeValueFromMarkup('<i class="icon status red"></i>, 1 - deleted')}"` );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM