Finds rich text in strings, ex: links, mentions, emails, your own parser, in an non overlapping way to prevent dubble matching.
Example
import{richStringParser}from'rich-string-parser'import{emailParser}from'rich-string-parser/lib/parsers/email-parser'import{linkParser}from'rich-string-parser/lib/parsers/link-parser'constresult=richStringParser('https://www.typescriptlang.org/ text example@example.com more text',[emailParser(),linkParser()],)// log result/* [ { type: 'LinkParser', match: 'https://www.typescriptlang.org/', index: 0, subIndex: 0 }, ' text ', { type: 'EmailParser', match: 'example@example.com', index: 37, subIndex: 37 }, ' more text'] */required parameters
{"type":"",// uniq for each parser"match":"",// result from parser"index":0,// where match is found based on whole string"subIndex":0// where match is found based on parsed substring}MentionParser
Matches on@(number|string), @(9712|John)
Result:
Without mention type:
{type:'MentionParser',match:'@(9712|John)',id:9712,name:'John',index:0,subIndex:0,target:undefined}With mention type provided:
{type:'MentionParser',match:'@(0|Testgroupchatroom|group)',id:0,name:'Testgroupchatroom',index:0,subIndex:0,target:'group'}EmailParser
Matches onexample@example.com,
Result:
{type:'EmailParser',match:'example@example.com',index:0,subIndex:0,}LinkParser
Matches onhttps://example.com,
Result:
{type:'LinkParser',match:'https://example.com',index:0,subIndex:0,}Create a function that retrurns aParser interface with a custom string in generic type, exampleParser<'HashtagParser'>.Implemente the required return object functionparse.
Example
functionhashtagParser():Parser<'HashtagParser'>{constregex:RegExp=/(#[a-z\d-]+)/gireturn{parse:(text,index)=>{constresult=regex.exec(text)if(result===null)returnnullreturn{type:'HashtagParser',match:result[0],index:index+result.index,// don't forget to add the global indexsubIndex:result.index,}},}}