Sunday 25 December 2022

Regex-rule for matching single word during input (TipTap InputRule)

I'm currently experimenting with TipTap, an editor framework. My goal is to build a Custom Node extension for TipTap that wraps a single word in <w>-Tags, whenever a user is typing text. In TipTap I can write an InputRule with Regex for this purpose

For example the rule /(?:^|\s)((?:~)((?:[^~]+))(?:~))$/ will match text between two tildes (~text~) and wrap it with <strike>-Tags.

Click here for my Codesandbox

I was trying for so long and can't figure it out. Here are the rules that I tried:

/**
 * Regex that matches a word node during input
 */

// Will match words between two tilde characters; I'm using this expression from the documentation as my starting point. 
//const inputRegex =  /(?:^|\s)((?:~)((?:[^~]+))(?:~))$/

// Will match a word but will append the following text to that word without the space inbetween
//const inputRegex =  /\b\w+\b\s$/

// Will match a word but will append the following text to previous word without the space inbetween; Will work with double spaces
//const inputRegex =  /(?:^|\s\b)(?:[^\s])(\w+\b)(?:\s)$/

// Will match a word but will swallow every second character
//const inputRegex =  /\b([^\s]+)\b$/g

// Will match every second word
//const inputRegex =  /\b([^\s]+)\b\s(?:\s)$/

// Will match every word but swallow spaces; Will work if I insert double spaces
const inputRegex =  /\b([^\s]+)(?:\b)\s$/


from Regex-rule for matching single word during input (TipTap InputRule)

No comments:

Post a Comment