_hyperscript icon indicating copy to clipboard operation
_hyperscript copied to clipboard

Regex syntax

Open danielnieto opened this issue 11 months ago • 4 comments

I want to sanitize the input value, I made this work:

    js 
      const regex = /[^a-zA-Z0-9-]/g
      return {regex}
    end

    on input 
      set my value to my value.replace(regex, '')
    end

I was wondering how can I avoid having to define the regex in JS and put it directly in HS, I didn't find any reference on RegExp on the documentation

danielnieto avatar Feb 10 '25 01:02 danielnieto

If I just use

    on input 
      set my value to my value.replace(/[^a-zA-Z0-9-]/g, '')
    end

I get this error:

Unexpected value: /

      set my value to my value.replace(/[^a-zA-Z0-9-]/g, '')
                                        ^^

danielnieto avatar Feb 10 '25 01:02 danielnieto

I changed the code and tried a lot but got error, regex is messed up in _hyperscript I think. 🤯

I think you can use what you write first one, at least less code than this 😶

<input _="
    on input 
      if my value's length > 0
        set @allowed to 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-' set @result to ''
        repeat for char in my value if @allowed contains char then set @result to @result + char end
        set my value to @result
      end
    end
">

At least it works 🤐

DeadLyBro avatar Jun 19 '25 12:06 DeadLyBro

I'm using the make command myself:

<button _="on click
	make a RegExp from '^\\d+$' called rex
	rex.test('123') then log it -- true
	rex.test('1a3') then log it -- false"></button>

, though it would be alot nicer to do it inline like JS is able to.

helpimnotdrowning avatar Aug 23 '25 18:08 helpimnotdrowning

Then this works too:

<input _="
    on input
        make a RegExp from '[^a-zA-Z0-9-]' called regex
        set my.value to my.value.replace(regex, '')
">

DeadLyBro avatar Aug 23 '25 19:08 DeadLyBro