Remove slashes from string using RegEx in JavaScript - javascript

I am trying to remove all special characters except punctuation from a customer complaint textarea using this code:
var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));
but it keeps placing "/" in front, and in back of the string after sanitizing.
Example:
Hi, I h#ve a% probl&em wit#h (one) of your products.
Comes out like this
/Hi, I have a problem with one of your products./
I want
Hi, I have a problem with one of your products.
Thanks in advance for any help given.

The variable complaint is converted to a regular expression because you use the RegExp() constructor.
This probably isn't what you want. (I assume you want complaint to be a string).
Strings and regular expressions are two completely different data types.
Your output demonstrates how JavaScript displays regular expressions (surrounded by / characters).
If you want a string, don't create a regular expression (i.e. remove the RegExp constructor).
In other words:
complaint = complaint.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

You don't need the RegExp constructor:
complaint = tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

Related

How do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

Jquery validate free emails using validator

I used jquery validator for validation.I have 50 free emails like(gmail.com, yahoo.com) so I need validate it.I chose an array then stored all the emails within an array.Below see my code there you could see I used the regular expression.I passed a variable in regular expression but it doesn't work for me.It threw the error like this SyntaxError: invalid range in character class
My code
$.validator.addMethod('nofreeemail', function (value) {
var emails = ["gmail.com","yahoo.com","hotmail.com"]
$.each(emails,function(i, val){
console.log("email", val)
var regex = new RegExp("/^([\w-.]+#(?!"+val+")([\w-]+.)+[\w-]{2,4})?$/");
console.log("regex", regex)
return regex.test(value);
});
}, 'Free email addresses are not allowed.');
I will post an answer since it is not evident here what is going on, but the underlying reasons are quite common.
You are using a constructor notation to define the regex. It is a correct approach when you need to build a pattern dynamically using a variable. However, a literal backslash must be written as "\\". All single backslashes are removed. Thus, you get an error since [\w-.] turns into [w-.] and it is an invalid character class. Also, the regex delimiters (those /..../ around the pattern) should never be used in the constructor notation unless you really need to match a string enclosed with /.
Besides, your emails contain non-word chars, and you need to escape them.
Use
var regex = new RegExp("^([\\w-.]+#(?!"+val.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')+")([\\w-]+\\.)+[\\w-]{2,4})?$");
I also believe the dot in ([\w-]+.)+ must be escaped, it is supposed to match a literal dot,

How to use a javascript Regex to globally find and replace the beginning of a string from a textarea

I am trying to replace any non encoded ampersands in a string in JavaScript and was wondering if this was possible. I have the regex build to detect this in the string, but when I do a replace, I will lose the parameter name.
Current input:
http://www.somesite.com/id/2343?paramA=1&paramB=asdf
From a textarea
<textarea id='test-box'>http://www.somesite.com/id/2343?paramA=1&paramB=asdf</textarea>
var str = $('#test-box').val();;
var regex = /&[a-z]+=/gi;
str = str.replace(regex, [REPLACE &'s WITH &'s]);
console.log(str);
Desired output:
http://www.somesite.com/id/2343?paramA=1&paramB=asdf
How can I then use JavaScript to keep the name of the parameter and simply replace the '&' with '&'?
Try this regex: /&(?=[a-z]+=)/ and this replacement: &
This uses a lookahead assertion rather than eating up the parameter name.
If you have a URL which might be partially encoded in HTML, and you're trying to make a best effort at producing XHTML validating textarea content, then you can use the list of HTML character references to identify ampersands which are not part of an HTML character reference:
str.replace(/&(?!#(?:[0-9]|[xX][0-9A-Fa-f])|lt;|gt;|amp|...)/g, '&')
where ... is replaced with the set of entities from that list that you care to recognize.
Note that most of those character references end in semicolon, so are not allowed to be followed immediately by an equals sign, so are not ambiguous with URL parameters. Only certain entities can appear without a semicolon for backwards compatibility.
If you don't care about validating, then you can just let the browser take care of it by ensuring that your URL doesn't contain the substring </textarea by doing something like
str.replace(/</g, '%3c')
Apart from lookahead assert, you can also use a backreference:
var regex = /&([a-z]+)=/gi;
str = str.replace(/&([a-z]+)=/gi,'&$1');
When $n appears in the replace string, it will be replaced by the n'th parenthesized pattern in the regexp.
Who needs regex when you've got jQuery html(). Especially since you've got a jquery tag on your question :D
What this does is leverage the browser's innerHTML property. see api
Fiddle
var str = 'http://www.somesite.com/id/2343?paramA=1&paramB=asd';
$('#test-box').text(str);
$('#html-box').text($('#test-box').html());

Regex validation rules

I'm writing a database backup function as part of my school project.
I need to write a regex rule so the database backup name can only contain legal characters.
By 'legal' I mean a string that doesn't contain ANY symbols or spaces. Only letters from the alphabet and numbers.
An example of a valid string would be '31Jan2012' or '63927jkdfjsdbjk623' or 'hello123backup'.
Here's my JS code so far:
// Check if the input box contains the charactes a-z, A-Z ,or 0-9 with a regular expression.
function checkIfContainsNumbersOrCharacters(elem, errorMessage){
var regexRule = new RegExp("^[\w]+$");
if(regexRule.test( $(elem).val() ) ){
return true;
}else{
alert(errorMessage);
return false;
}
}
//call the function
checkIfContainsNumbersOrCharacters("#backup-name", "Input can only contain the characters a-z or 0-9.");
I've never really used regular expressions before though, however after a quick bit of googling i found this tool, from which I wrote the following regex rule:
^[\w]+$
^ = start of string
[/w] = a-z/A-Z/0-9
'+' = characters after the string.
When running my function, the whatever string I input seems to return false :( is my code wrong? or am I not using regex rules correctly?
The problem here is, that when writing \w inside a string, you escape the w, and the resulting regular expression looks like this: ^[w]+$, containing the w as a literal character. When creating a regular expression with a string argument passed to the RegExp constructor, you need to escape the backslash, like so: new RegExp("^[\\w]+$"), which will create the regex you want.
There is a way to avoid that, using the shorthand notation provided by JavaScript: var regex = /^[\w]+$/; which does not need any extra escaping.
It can be simpler. This works:
function checkValid(name) {
return /^\w+$/.test(name);
}
/^\w+$/ is the literal notation for new RegExp(). Since the .test function returns a boolean, you only need to return its result. This also reads better than new RegExp("^\\w+$"), and you're less likely to goof up (thanks #x3ro for pointing out the need for two backslashes in strings).
The \w is a synonym for [[:alnum:]], which matches a single character of the alnum class. Note that using character classes means that you may match characters that are not part of the ASCII character encoding, which may or may not be what you want. If what you really intend to match is [0-9A-Za-z], then that's what you should use.
When you declare the regex as a string parameter to the RegExp constructor, you need to escape it. Both
var regexRule = new RegExp("^[\\w]+$");
...and...
var regexRule = new RegExp(/^[\w]+$/);
will work.
Keep in mind though, that client side validation for database data will never be enough, as the validation is easily bypassed by disabling javascript in the browser, and invalid/malicious data can reach your DB. You need to validate the data on the server side, but preventing the request with invalid data, but validating client side is good practice.
This is the official spec: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html but it's not very easily converted to a regular expression. Just a regular expression won't do it as there are also reserved words.
Why not just put it in the query (don't forget to escape it properly) and let MySQL give you an error? There might for instance be a bug in the MySQL version you're using, and even though your check is correct, MySQL might still refuse.

Javascript regexp lets undesirable characters

I'm using a regExp in my project but some how I'm getting some undesirable characters
my RegExp looks like this:
new RegExp("[א-ת,A-z,',','(',')','.','-',''']");
which supposed to avoid characters like \ or []
but let my use one and more from (,),-,alphabets etc.
Unfortunately it doesnt happen
Which pattren includes both desirable and undesirable characters??
thanks for your help
Well your regular expression just says to match one "good" character (and incorrectly at that).
I think something closer to this would be what you want, though I'm not sure about the higher-page UTC characters:
var regexp = /^[א-תA-Za-z,()\-']*$/;
If the alefbet part doesn't work (it looks backwards to me, but I guess that's kind of a conundrum :-), try:
var regexp = /^[\u05DA-\05EAA-Za-z,()\-']*$/;
Might be good to tack an "i" (ignore case) modifier on the end too:
var regexp = /^[\u05DA-\05EAA-Za-z,()\-']*$/i;
This also does not handler the various diacritical marks; I don't know if you need those matched or not.
First of all, you don't need all those single quotes and commas. Second, you want A-Za-z, not.A-z. The latter includes ASCII characters between "Z" and "a".
var re = new RegExp("[א-תA-Za-z,()\.'\s-]");

Categories

Resources