how to get value of text which is outside a tag

Solution for how to get value of text which is outside a tag
is Given Below:

I need to extract a text from the code snippet below (Using Protractor)

<mat-chip>
<div class="mat-chip-ripple"></div>
 "Text to print'
<mat-icon>cancel</mat-icon>
</mat-chip>

I want to my function to return ‘Text to print’ only.
Doing a getText() on element gives me
‘Text to Print’ and ‘cancel’ too.

Other options I tried was elem.getAttribute(‘innerHTML’) & ‘innerText’ – none provided me the answer I was looking for

Yes, your text is in a tag, the problem is that between the text and the beginning of tag there is another tags, but that does not matter to get the text.

For the code that you provide, if you want to take the text “Text to print’ you should take the text from <mat-chip> element. Something like:

element(by.xpath("//mat-chip")).getText()

For the element which contains cancel, you should take the text from <mat-icon> element:

element(by.xpath("//mat-icon")).getText()