2

I've a very simple question. I've a sanitized string and its type in Angular is SafeHtml.

How would be the best approach to search and replace some Html inside this SafeHtml variable?

...

const sanitzedHtml: SafeHtml = this.sanitizer.bypassSecurityTrustHtml(changes.pureHtml.currentValue);

...

My goal is to replace some string with some extra html code, so the best would be to be able to search only within the html nodes, not really everywhere in the code.

Are there faster way than reconverting the SafeHtml variable into a string and apply a basic replace with a RegExp?

Thanks

1 Answer 1

0

Change HTML code before sanitize

1 - Using regex

You can change your code by using Regex on your html string, then sanitize it.

let html = "<div>myHtml</div>"
const regex = /myRegexPattern/i;
html.replace(regex, 'Replacement html part'));

2 - Using DocumentFragment

You can also create a fragment of your html, modify what you want in it and string it before start your sanitize function

let str:string = "<div id='test'>myHtml</div>";
const sanitzedHtml:SafeHtml = this.sanitizer.bypassSecurityTrustHtml(changeMyHtml(str));

function changeMyHtml(htmlString:string):string{
    let fragment= document.createRange().createContextualFragment(str);
    //do what you need to do here like for exemple
    fragment.getElementById('test').innerHtml = "myHtmlTest";
    //then return a string of the modified html
    const serializer = new XMLSerializer();
    return serializer.serializeToString(element)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.