Regex to trim white space and special characters from an input string before submission
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2023 03:39 AM
Hi Team,
There is a requirement to trim white spaces and special characters from an input string before it gets submitted.
Ex. If user is inputting space in beginning and after the text ends and more than one space in between then it should get trimmed.
<space><space><space><tab>TEST<space>TEST1<space><space><tab>TEST2<space><space><space>
should become
TEST<space>TEST1<space>TEST2 ( With only one space in between )
Moreover only these characters could be allowed : ( ) & - (brackets, ampersand and hyphen) and no other characters
Ex. TEST - TEST1
TEST & TEST1
(TEST)
It will be great if someone could help me with the regex logic.
Regards,
Saurabh

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2023 06:44 AM - edited 05-25-2023 06:47 AM
I am not clear on the full format of your input, so assuming that your input can contain multiple lines, you can try the snippet below to remove the unwanted characters that I know of.
user_data
.split('\n') // Break up the multi-row input into rows
.map( function( row ){ // clean up each row
row = row.trim(); // Remove the leading and trailing white spaces.
row = row.replace( /[^\w\d &\-\(\)\.]/g, '' ); // Remove the characters that are not wanted.
return row;
} )
.join('\n'); // Put it all back together again.
Using the sample below:
%percent
#pound
@at
*star
Ex. TEST - TEST1
TEST & TEST1
(TEST)
The result is:
percent
pound
at
star
Ex. TEST - TEST1
TEST & TEST1
(TEST)
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2023 06:54 AM
Hi @John Dahl ,
Thank you so much for your reply!
The input is only a single-line text. In that case what will be my regex logic?
Regards,
Saurabh

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2023 07:02 AM - edited 05-25-2023 07:05 AM
In that case, you just skip the split, map, and join steps.
Given the following input:
user_data = " %percent (test) & TEST - Test "
Note: There are multiple leading and trailing whitespace characters in that input.
Running this script:
// Note that you need to save the result back into the variable.
user_data = user_data
.trim()
.replace( /[^\w\d &\-\(\)\.]/g, '' );
Would result in this output:
"percent (test) & TEST - Test"
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2023 07:14 AM
Hi @John Dahl ,
Actually I need to add this regex condition in "Validation Regex" field against the field name and in order to do so I will need to first define it in "question_regex" table.
Will it work if I add the same in the 'Regular Expression' box?
Regards,
Saurabh