C
C#2y ago
johnrudy

✅ Remove tags from string

So if I have a string like this This is a string with <color="red">different colors</color>. And some cool <shake>other effects</shake> How can I remove the tags from the string and leave the rest as is? I was thinking of looking into the string and removing everything between < and > but I can't seem to find a solution that would do that. Any suggestions?
10 Replies
Spectra
Spectra2y ago
if you can use regex it's pretty easy. Regex.Replace(inputString, "<.*?>", "");
johnrudy
johnrudyOP2y ago
oooh I wasn't aware regex was in c# that's nice I'll try that. Thanks
Angius
Angius2y ago
Pretty much every language has some sort of regex support But... what if the string is <foo>two < three</foo>? What if it's <foo>a -> b -> c</foo>?
johnrudy
johnrudyOP2y ago
True. Might be situations where it's desired to have those within. But I think for now I can live without. I guess the string would need to have some escape string type deal.
Angius
Angius2y ago
One of the reasons you never really sanitize for HTML nowadays, you just escape it Instead of stripping all <script>s and the like, you just display it as &lt;script&gt;
johnrudy
johnrudyOP2y ago
I'm not sanitizing html 😄 Doing an dialog system that has text styling tags in it
Angius
Angius2y ago
You're looking at making some parser, then Or using something existing like BBCode
johnrudy
johnrudyOP2y ago
Sorry, should've added that in the question. a custom parser yeah
Angius
Angius2y ago
Ah, well, you should tokenize it then, into something like
[
{str: "This is a string with "},
{str: "different colors", color: Colors.Red},
{str: ". And some cool"},
{str: "other effects", effect: new Shake()}
]
[
{str: "This is a string with "},
{str: "different colors", color: Colors.Red},
{str: ". And some cool"},
{str: "other effects", effect: new Shake()}
]
If you do that, no need to strip anything And with a parser like this you already keep track of <s and >s, so it should be easy to tell which strings are not parts of the tags at that stage
johnrudy
johnrudyOP2y ago
True, I might actually do that. Because the more I think of it the more confusing it gets. Yeah, I'll have to take a closer look at that. To be honest this has now made me rethink my entire system so I might just re do it. Thanks for the advice everyone.
Want results from more Discord servers?
Add your server