i am trying only to allow numerals and special chars like '.' and ',' to be allowed in my text string. for that i have tried following code
var pattern = /[A-Za-z]/g;
var nospecial=/[\(#\$\%_+~=*!|\":<>[\]{}`\\)';#&?$]/g;
if (!ev.ctrlKey && charCode!=9 && charCode!=8 && charCode!=36 && charCode!=37 && charCode!=38 && (charCode!=39 || (charCode==39 && text=="'")) && charCode!=40) {
console.log(text);
if (!pattern.test(text) && !nospecial.test(text)) {
console.log('if');
return true;
} else {
console.log('else');
return false;
}
}
but not getting the desired output. tell me where i am wrong.
Forget trying to blacklist, just do this to allow what you want:
var pattern = /^[0-9.,]*$/;
Edit: Also, rather than just checking for numbers, commas, and dots. I'm assuming something like this do even more than you were hoping for:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
So why don't you try /^[0-9,.]*$/ instead of negating the test?
You can try this:
/([0-9]+[.,]*)+/
It will matche number with or withot coma or dots.
^(?!.*[^0-9.,\n]).*$
Not sure of what you mean by efficient but this fails faster though it takes long to match correct string.See demo.
http://regex101.com/r/aK2zV7/1
You could also just use the solution from this answer:
parseFloat(text.replace(',',''));
Related
I have a form validator by AntonLapshin where I'm trying to validate a non-empty input field which can only take alphabets, space, - and '. The alphabets can be a-z, A-Z and europian letters æÆøØåÅöÖéÉèÈüÜ, etc. See this for more details.
Here is what I am doing:
method : function(input) {
return input.value !== ''
&& input.value === /^[a-zA-Z'\- \u00c0-\u017e]+$/
}
Here, it should match: Åløæ-Bond Mc'Cool
But fail: 123-Bond Mc'C#o!
When I run ^[a-zA-Z'\- \u00c0-\u017e]+$ in regex tester, It works absolutely fine, but in my script, it is not validating and throws an invalid input error.
What am I doing wrong?
I prefer to use RegExp. You also need to do return pattern.test(input)
This will work :)
var test1 = "Åløæ-Bond Mc'Cool";
var test2 = "123-Bond Mc'C#o!";
var pattern = new RegExp(/^[a-zA-Z'\- \u00c0-\u017e]+$/);
function regextest(input) {
return input !== '' && pattern.test(input)
}
console.log(regextest(test1))
console.log(regextest(test2))
modify your function to test with regex
var pattern = /^[a-zA-Z'\- \u00c0-\u017e]+$/
var method = function(input) {
return input !== '' &&
pattern.test(input)
}
//your sample strings
console.log(method("Åløæ-Bond Mc'Cool"))
console.log(method("123 - Bond Mc 'C#o!"))
I figured out a simpler solution for my question:
method : function(input) {
return input.value !== '' && /^[a-zA-Z'\- \u00c0-\u017e]+$/.test(input.value)
}
The problem was, after the && operator, I was checking for the input value (that’s wrong in regex check) instead of Boolean value.
This solution works perfectly and creates no confusion.
Answer #Wiktor Stribiżew suggested:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
}
Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array
function myValidate(word) {
// No one letter words
if (word.length === 1) {
return true;
}
if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
return true;
}
return false;
}
It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:
if (word.match('/[^A-Za-z]+/g') ) {
return true;
}
can some one shed some light on the proper way of handling this?
I suggest using a simpler solution:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? false : true;
}
var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"];
document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));
Where:
word.length === 1 checks for the string length
/[^A-Z]/i.test(word) checks if there is a non-ASCII-letter symbol in the string
If any of the above condition is met, the word is taken out of the array. The rest remains.
EDIT: using test instead of match
You want to use test() because it returns a bool telling you if you match the regex or not. The match(), instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.
To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):
return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words
You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:
if (word.test('/^[a-zA-Z]+$/')) { // two letter words
return false;
}
This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.
Your regex, instead, looked for illegal characters by negating the character group with the leading ^.
Two recommendations:
Just use regex in a positive way (without negation) and it'll be a lot easier to understand.
Also, validation functions normally return true for good data and false for bad data.
It is more readable this way:
if (validate(data))
{
// that's some good data we have here!
}
this might be a very basic question, but I would like to know how I can find out if .html() has a particular value (in this case a string). An example:
<p id="text">Hello this is a long text with numbers like 01234567</p>
and I would like to ask
var $text = $('#text');
if ($text.html() == '01234567')
of course this would not work. But how can I enhance another method to .html() that asks
if($text.html().contains() == '01234567');
Important to say is, that in my case I definitely will search for things who are seperated with a space, not like withnumberslike01234567 but indeed it would be interesting if that would work as well.
Thanks in advance!
(' ' + document.getElementById('text').textContent + ' ').indexOf(' 01234567 ') != -1
Fixes problem with the text at the beginning, doesn't abuse regex, and hooray for vanilla.js!
You can use indexOf:
var text = $('#text').html();
if(text.indexOf(" 01234567") != -1) {
// your logic
}
Your HTML might start with 01234567, though; in that case, you can do this:
if((' ' + text).indexOf(" 01234567") != -1) {
// your logic
}
Thanks, bjb568 and Felix Kling.
As I understand from OP, these are the test cases:
hello12348hello // false
hello 1234hello // false
hello012348 hello // false
hello 1234 hello // TRUE
1234hello // false
hello1234 // false
1234 hello // TRUE
hello 1234 // TRUE
// false
1234 // TRUE
1234 // TRUE
** Changing "" by any other white-space character (e.g. \t, \n, ...) should give same results.
As OP said:
for things who are separated with a space, not like withnumberslike01234567
So, hello 01234567withnumberslike is also wrong!!!
Creating the function:
function contains(value, searchString){
// option 1: splitting and finding a word separated by white spaces
var words = value.split(/\s+/g);
for (var i = 0; i < words.length; i++){
if (words[i] === searchString){
return true;
}
}
return false;
// option 1a: for IE9+
return value.split(/\s+/g).indexOf(searchString) > -1;
// option 2: using RegEx
return (new RegExp("\\b" + searchString + "\\b")).test(value);
return (new RegExp("(^|\\s)" + searchString + "($|\\s)")).test(value); // this also works
// option 3: Hardcoded RegEx
return /\b1234\b/.test(value);
}
See case tests here in jsFiddle
It will also accept tabs as well as whitespaces..
NOTE I wouldn't worry about using RegEx, it isn't fast as indexOf, but it stills really fast. It shouldn't be an issue, unless you iterate millions of times. If it would be the case, perhaps you'll need to rethink your approach because probably something is wrong..
I would say to you think about compatibility, there is a lot of users still using IE8, IE7, even IE6 (almost 10% right now - April, 2014). -- No longer an issue in 2016..
Also, it's preferred to maintain code standards.
Since, you are using jQuery you can use too .text() to find string:
var element = $(this);
var elementText = element.text();
if (contains(elementText, "1234"){
element.text(elementText.replace("1234", "$ 1234.00"))
.addClass("matchedString");
$('#otherElement').text("matched: 1234");
}
Thanks to #Karl-AndréGagnon for the tips.
\b: any boundary word (or start/end of the string)
^: start of the string
\s: Any whitespace character
$: end of the string
http://rubular.com/r/Ul6Ci4pcCf
You can use the String.indexOf method in JavaScript to determine whether or not one string is contained in another. If the string passed into indexOf is not in the string, then -1 is returned. This is the behavior you should utilize.
If ($test.html().indexOf("1234567890") != -1)
//Do Something
if($text.html().indexOf('01234567') != -1) {
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}
What is the best way to check if a single character is a whitespace?
I know how to check this through a regex.
But I am not sure if this is the best way if I only have a single character.
Isn't there a better way (concerning performance) for checking if it's a whitespace?
If I do something like this. I would miss white spaces like tabs I guess?
if (ch == ' ') {
...
}
If you only want to test for certain whitespace characters, do so manually, otherwise, use a regular expression, ie
/\s/.test(ch)
Keep in mind that different browsers match different characters, eg in Firefox, \s is equivalent to (source)
[ \f\n\r\t\v\u00A0\u2028\u2029]
whereas in Internet Explorer, it should be (source)
[ \f\n\r\t\v]
The MSDN page actually forgot the space ;)
The regex approach is a solid way to go. But here's what I do when I'm lazy and forget the proper regex syntax:
str.trim() === '' ? alert('just whitespace') : alert('not whitespace');
I have referenced the set of whitespace characters matched by PHP's trim function without shame (minus the null byte, I have no idea how well browsers will handle that).
if (' \t\n\r\v'.indexOf(ch) > -1) {
// ...
}
This looks like premature optimization to me though.
this covers spaces, tabs and newlines:
if ((ch == ' ') || (ch == '\t') || (ch == '\n'))
this should be best for performance. put the whitespace character you expect to be most likely, first.
if performance is really important, probably best to consider the bigger picture than individual operations like this...
While it's not entirely correct, I use this pragmatic and fast solution:
if (ch.charCodeAt(0) <= 32) {...
#jake 's answer above -- using the trim() method -- is the best option. If you have a single character ch as a hex number:
String.fromCharCode(ch).trim() === ""
will return true for all whitespace characters.
Unfortunately, comparison like <=32 will not catch all whitespace characters. For example; 0xA0 (non-breaking space) is treated as whitespace in Javascript and yet it is > 32. Searching using indexOf() with a string like "\t\n\r\v" will be incorrect for the same reason.
Here's a short JS snippet that illustrates this: https://repl.it/#saleemsiddiqui/JavascriptStringTrim
Based on this benchmark, it appears the following method would be most performant:
For Performance:
function isWhitespace(c) {
return c === ' '
|| c === '\n'
|| c === '\t'
|| c === '\r'
|| c === '\f'
|| c === '\v'
|| c === '\u00a0'
|| c === '\u1680'
|| c === '\u2000'
|| c === '\u200a'
|| c === '\u2028'
|| c === '\u2029'
|| c === '\u202f'
|| c === '\u205f'
|| c === '\u3000'
|| c === '\ufeff'
}
There are, no doubt, some cases were you might want this level of performance (I'm working on a markdown converter and am trying to squeeze out as much performance as possible). However, in most cases, this level of optimization is unnecessary. In such cases, I would recommend something like this:
For Simplicity:
const whitespaceRe = /\s/
function isWhitespace(c) {
return whitespaceRe.test(c)
}
This is more readable, and less likely to have a typo and, therefore, less likely to have a bug.
var testWhite = (x) {
var white = new RegExp(/^\s$/);
return white.test(x.charAt(0));
};
This small function will allow you to enter a string of variable length as an argument and it will report "true" if the first character is white space or "false" otherwise. You can easily put any character from a string into the function using the indexOf or charAt methods. Examples:
var str = "Today I wish I were not in Afghanistan.";
testWhite(str.charAt(9)); // This would test character "i" and would return false.
testWhite(str.charAt(str.indexOf("I") + 1)); // This would return true.
function hasWhiteSpace(s) {
return /\s/g.test(s);
}
This will work
or
you can also use this indexOf():
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
how about this one :
((1L << ch) & ((ch - 64) >> 31) & 0x100002600L) != 0L