Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Find tokens in your strings

License

NotificationsYou must be signed in to change notification settings

richie-south/javascript-rich-string-parser

Repository files navigation

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'] */

Parser result

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}

Built in parsers

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 your own parser

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,}},}}

About

Find tokens in your strings

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp