Home > other >  Is it possible to remove a whole string that is left from a certain character
Is it possible to remove a whole string that is left from a certain character

Time:01-25

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.

Here is an example of the stuff i get in the string :

<i ></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. 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 ?

CodePudding user response:

Why would you run forEach loop. with slice and split, you can have the string like you want, here you go:

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

let list = string.split(",")

console.log(list[1])

CodePudding user response:

One could utilize DOMParser and DOMParser.parseFromString in order to access just text content ...

function getTextContentFromMarkup(markup) {
  return new DOMParser()
    .parseFromString(markup, "text/html")
    .body
    .textContent;
}

console.log(
  `getTextContentFromMarkup('<i ></i>, 1 - deleted') ...
  "${ getTextContentFromMarkup('<i ></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 ></i>, 1 - deleted') ...
  "${ getLastTextNodeValueFromMarkup('<i ></i>, 1 - deleted')}"`
);

  •  Tags:  
  • Related