Reputation: 45
What I am trying to do is clean up an input field on blur. My blur code is completely functional, but I can't get the regex to work correctly. All of the characters I'm trying to allow are working correctly except for any number of line breaks. I've tried with different variations and combinations of including /s, /r, and /n .
I am doing this because I want to prevent as many characters that don't really belong in a descriptive input field as possible. I am using entity to linq for database input, which should protect me from sql injection attacks, but I still want to restrict the characters for added security. I am allowing apostrophes, but that should be the only potential threat from the allowed characters listed in the regex below.
Once I get the regex, I'll also replace on paste using the same code block.
This is my javascript method that I reverted back to.
function CleanSentenceInput(AlphaNumString) {
input = AlphaNumString;
var CleanInput = input.replace(/[^a-z0-9\s.,;:'()-]/gi, '');
CleanInput = myTrim(CleanInput);
return CleanInput;
}
Is there a way to allow any number of line breaks by modifying this replace regex?
Test Input:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
cccccccccccccccc
Test Result:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccc
Expected Result:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
cccccccccccccccc
Update ** It turns out that the trim function I was using was removing the line-breaks. Here is that function:
Bad trim function:
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm, '');
}
Is there a way to fix this regex so that it still replaces whitespace before and after, but not inside of the content?
Updated **
Good Trim Function:
function myTrim(x) {
return x.replace(/^\s+|\s+$/g, '');
}
Upvotes: 2
Views: 946
Reputation: 626689
As I noted from the beginning the problem is not with the regex since
/[^a-z0-9\s.,;:'()-]/gi
matches characters other than whitespace (beside others in the character class).
In MyTrim
you need to remove m
because otherwise, $
is treated as a line end and ^
as line start anchors, and in fact you want to only trim the string from its beginning and end:
function myTrim(x) {
return x.replace(/^\s+|\s+$/g, '');
}
It is also possible to use trim()
(it is supported by all modern browsers, IE9 already should support it).
Upvotes: 1