linkifyjs icon indicating copy to clipboard operation
linkifyjs copied to clipboard

Trying to add & detect custom prefixes

Open Goatform opened this issue 3 years ago • 3 comments

Hey, I recently ran into this plugin and started using it. I'm trying to find a way to detect and linkify custom prefixes ... e.g. UID-123123. Also, I did look into plugins such as mention and hashtag but it still wasn't completely clear to me as there didn't seem to be a way to add a custom prefix, be it a single or multiple prefix check, in a plugin. What would be the best way to detect if the string contains the UID- prefix if so, because, either I am missing something in documentation or there's really no way (currently) to do such a thing. I'd appreciate any suggestion regarding this if so, please and thank you.

Goatform avatar Dec 01 '21 11:12 Goatform

I'm also looking for the exact same thing. An easy to way to customize prefixes or more documentation around writing custom plugins would be really helpful for this use case.

robertn702 avatar Apr 24 '22 08:04 robertn702

After reading https://github.com/Hypercontext/linkifyjs/issues/167#issuecomment-1018668663 and looking at the existing plugins I tried to create a custom plugin that looks for something like UID-123 but I failed:

import { createTokenClass, registerTokenPlugin, registerPlugin, tokenize, stringToArray} from 'linkifyjs';
import linkifyStr from 'linkify-string';

const PrefixToken = createTokenClass('prefix', {
  isLink: true,
  toHref() {
    return `https://example.com/${this.toString()}`
  }
})

registerTokenPlugin('prefix', ({scanner}) => {
  scanner.start.ts(stringToArray('UID'), 'UID');
})

registerPlugin('uid', ({parser, scanner}) => {
  const {HYPHEN, NUM, WORD} = scanner.tokens
  // @ts-ignore
  parser.start.tt('UID').tt(HYPHEN).tt(NUM, PrefixToken);
})

const str = 'UID-123 UI-123 abc https://google.com https://example.com/UID-123 defg';
console.log(tokenize(str));
console.log(linkifyStr(str))

The returned tokens look like this: grafik

UID was not recognized as a UID token but as a WORD token, so I think I am doing something wrong in the registerTokenPlugin part.

Using

registerPlugin('uid', ({parser, scanner}) => {
  const {HYPHEN, NUM, WORD} = scanner.tokens
  // @ts-ignore
  parser.start.tt(WORD).tt(HYPHEN).tt(NUM, PrefixToken);
})

instead works, but now any WORD HYPHEN NUM sequence will be recognized, not only parts starting with UID: grafik

WIStudent avatar Jun 06 '23 17:06 WIStudent

@WIStudent I think the problem is that linkify is not implemented with the case sensitivity, which makes plug-in registration finicky sometimes. Try replacing the registerTokenPlugin call with this:

registerTokenPlugin('prefix', ({scanner}) => {
  scanner.start.ts(stringToArray('uid'), 'UID', {ascii: true});
})

nfrasser avatar Jun 08 '23 14:06 nfrasser