Why does String(value).replace(/[^0-9.-]/g, '') work? - javascript

I saw String(value).replace(/[^0-9.-]/g, '') from a library that described to filter illegal characters, and finally it will return the legal number. Why does this work and what will really be replaced? I feel confused because I think nothing will be replaced.
For example:
String("1.absd").replace(/[^0-9.-]/g, '')
// '1.'

String(value) will make string from value. So if you use number, this will convert it to string, because function replace is defined only from string.
replace(/[^0-9.-]/g, '') this will replace any matching given regular expression with empty string. In regular expression you have [^0-9.-]. The ^ at start means, that any characters not from this interval will match. So any character other than number, dot or -. Modifier g after slash means, that this regular expression is global and will be applied for all matches
so from "1.absd" the characters "absd" will be replaced with empty string

Related

javascript regexp does not evaluate only one character

I'm using this regexp:
/[^+][a-z]/.test(str)
I'm trying to ensure that if there are any letters ([a-z]) in a string (str) not proceeded by a plus ([^+]) , a match is found and therefore it will return true.
It mostly works except when there is only one character in the string. For example, a returns false, even though there is no plus sign preceding it.
How can I ensure it works for all strings including one character strings. Thanks!
Add a ^ as an alternative to [^+]:
/(?:^|[^+])[a-z]/.test(str)
^^^^^^^^^^
The (?:^|[^+]) is a non-capturing alternation group matching either the start of the string (with ^) or (|) any char other than + (with [^+]).

string.prototype.search('$') returns positive int on every string

I want to check if a string contains any of several symbols, including '$'. But the string.prototype.search() method returns last character index + 1 when searching for '$'
For example:
'abc'.search('$') //return 3
''.search('$') //return 0
I want to know why this is happening
From MDN:
regexp
Optional. A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
So your call is equivalent to:
'abc'.search(/$/);
$ in a regular expression matches the end of the string. If you want to disable the special meaning, you need to escape it:
'abc'.search('\\$')
You need two \ characters: the first escapes the backslash in the string literal, and this then escapes the dollar sign in the regexp. Or you could write:
'abc'.search(/\$/)

Exact match a string using Regular Expression in JavaScript

I want to validate a string in JavaScript to allow alphanumerics, "(", ")" , and spaces. So test strings are:
s1 = "This $h00l*&^ not w0rk342*_(&, <and> always fail"
s2 = "This should work (ABC1234)"
my code:
var regX = new RegExp(/A-Za-z0-9\\(\\)\\x20+/);
if(!regX.test(s1)){
alert("InValid value.");
}
But it fails for both the strings.
Also as test() function evaluates the matches in the string and not the whole string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Can someone please help. Thanks in advance
You should use this regex:
/^[A-Za-z0-9() ]*$/
Replace * with + if you don't want to allow empty string.
^ and $ test for beginning and the end of the string respectively.
* means repeat 0 or more times. + means repeat once or more.
To specify a character class (i.e. a set of character), you need to place the characters inside [].
To further shorten the regex:
/^[a-z\d() ]*$/i
i flag will make the regex matches case-insensitively, which remove the needs to specify A-Z.
\d is the shorthand character class for digits 0-9. Shorthand character class can also be included inside character class.

jQuery Regular Expression Returns Unexpected Results

I'm trying to use the following code with jQuery to validate hex value strings but I get unexpected results:
var a = new RegExp("0x[a-fA-F0-9]+")
var result = a.test('0x1n')
In this case, result actually returns true. What am I missing here?
You need anchors to match the beginning and the end of the string. This will make the regular expression try to match against the entire string instead of just a part of the string:
var a = new RegExp("^0x[a-fA-F0-9]+$")
Otherwise your regular expression matches the 0x1 part and returns true.
On another note, the following would be a little better:
var re = /^0x[a-f0-9]+$/i;
The i flag makes it case insensitive so you don't have to specify a-f and A-F.
Your regex does match that string, because you don't have any anchors on it. If you change your regex to ^0x[a-fA-F0-9]+$, then the string 0x1n will not match.
Edit: To further explain why your string matches, your regular expression is actually trying to match a string that contains 0x followed by one or more characters in the [a-fA-F0-9] character class. The string 0x1n contains 0x followed by 1, which is in the [a-fA-F0-9] character class.
Adding anchors means that your string must start with 0x, then finish with one or more characters in the [a-fA-F0-9] character class. 0x1n would fail to match, since it ends in an n, which is not in that character class.
It returns true because you're not requiring the entire string to match that pattern. Try this:
var a = new RegExp("^0x[a-fA-F0-9]+$")

Javascript String pattern Validation

I have a string and I want to validate that string so that it must not contain certain characters like '/' '\' '&' ';' etc... How can I validate all that at once?
You can solve this with regular expressions!
mystring = "hello"
yourstring = "bad & string"
validRegEx = /^[^\\\/&]*$/
alert(mystring.match(validRegEx))
alert(yourstring.match(validRegEx))
matching against the regex returns the string if it is ok, or null if its invalid!
Explanation:
JavaScript RegEx Literals are delimited like strings, but with slashes (/'s) instead of quotes ("'s).
The first and last characters of the validRegEx cause it to match against the whole string, instead of just part, the carat anchors it to the beginning, and the dollar sign to the end.
The part between the brackets ([ and ]) are a character class, which matches any character so long as it's in the class. The first character inside that, a carat, means that the class is negated, to match the characters not mentioned in the character class. If it had been omited, the class would match the characters it specifies.
The next two sequences, \\ and \/ are backslash escaped because the backslash by itself would be an escape sequence for something else, and the forward slash would confuse the parser into thinking that it had reached the end of the regex, (exactly similar to escaping quotes in strings).
The ampersand (&) has no special meaning and is unescaped.
The remaining character, the kleene star, (*) means that whatever preceeded it should be matched zero or more times, so that the character class will eat as many characters that are not forward or backward slashes or ampersands, including none if it cant find any. If you wanted to make sure the matched string was non-empty, you can replace it with a plus (+).
I would use regular expressions.
See this guide from Mozillla.org. This article does also give a good introduction to regular expressions in JavaScript.
Here is a good article on Javascript validation. Remember you will need to validate on the server side too. Javascript validation can easily be circumvented, so it should never be used for security reasons such as preventing SQL Injection or XSS attacks.
You could learn regular expressions, or (probably simpler if you only check for one character at a time) you could have a list of characters and then some kind of sanitize function to remove each one from the string.
var myString = "An /invalid &string;";
var charList = ['/', '\\', '&', ';']; // etc...
function sanitize(input, list) {
for (char in list) {
input = input.replace(char, '');
}
return input
}
So then:
sanitize(myString, charList) // returns "An invalid string"
You can use the test method, with regular expressions:
function validString(input){
return !(/[\\/&;]/.test(input));
}
validString('test;') //false
You can use regex. For example if your string matches:
[\\/&;]+
then it is not valid. Look at:
http://www.regular-expressions.info/javascriptexample.html
You could probably use a regular expression.
As the others have answered you can solve this with regexp but remember to also check the value server-side. There is no guarantee that the user has JavaScript activated. Never trust user input!

Categories