Related to Properly simulate "pattern" attribute with javascript:
How do I set an input pattern using JavaScript?
when I try element.pattern = 'a\S' (as a trivial example), then the pattern ends up in aS (with the backslash being removed).
The same happens with
element.pattern = `a\S`
Of course I could double the backslash, but I'd like to create the javascript using a string constant that is used in CGI's textfield({-pattern => PATTERN}).
A bit like this:
#...perl part to create initial HTML element...
textfield(-pattern => PERL_PATTERN, ...);
#...creating JavaScript to add or remove pattern dynamically
element = document.getElementById(...);
if (...)
element.pattern = `${\PERL_PATTERN}`;
else
element.removeAttribute('pattern');
I'd like to avoid something ugly as
use constant PERL_PATTERN => 'a\S';
use constant JAVASCRIPT_PATTERN => PERL_PATTERN =~ s/\\/\\\\/gr;
to duplicate the pattern, but with backslashes doubled. Is there a way to keep the backslash in JavaScript?
perl -e 'use constant PERL_PATTERN => q"a\S"; use constant JAVASCRIPT_PATTERN => quotemeta(PERL_PATTERN); print "${\JAVASCRIPT_PATTERN}\n";'They actually both work for me, but I suspect javascript may need the backslash to be escaped, andquotemetashould work.use constant JAVASCRIPT_PATTERN => PERL_PATTERN =~ s/\\/\\\\/grI do not like.\Ssomehow. Maybeuse constant PERL_PATTERN => "a\\S";which is just another way to escape it manually. All that will work. There are many ways to escape it manually, but if you want something different or unusual I dont know there is anything.