I'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm looking for. I have a function here:
function findCertainWords()
{
var t = {Some text value};
if (t in {'one':'', 'two':''})
return alert("At least one string is found. Change them."), 0;
return 1
}
Variable a is user's written text (for example, a comment or a post).
I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.
It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.
Use indexOf to test if a string contains another string. Use .toLowerCase to convert it to one case before comparing.
function findCertainWords(t) {
var words = ['one', 'two'];
for (var i = 0; i < words.length; i++) {
if (t.toLowerCase().indexOf(words[i]) != -1) {
alert("At least one string was found. Change them.");
return false;
}
}
return true;
}
Another way is to turn the array into a regexp:
var regexp = new RegExp(words.join('|'));
if (regexp.test(t)) {
alert("At least one string was found. Change them.");
return false;
} else {
return true;
}
You can use Array.some with Object.keys
if(Object.keys(obj).some(function(k){
return ~a.indexOf(obj[k]);
})){
// do something
}
Related
Regex left for
(Must not contain sequences of letters or numbers) and
(Do not repeat a number or letter more than 5 times).
I know its repeated question but I was not able to find combination of my requirement. When I tried to combine I was getting errors
Other than that I was able to do it
I was trying for not repeating more than 5 but this one is not working
`^(?=.*?[a-zA-Z])(?=.*?[0-9])((.)\2{0,4}(?!\2)).{6,15}$`
Partially working one is ^(?=.*?[a-zA-Z])(?=.*?[0-9]).{6,15}$ I need to both conditions in it.
As suggested, have a RegExp that checks the string for allowed characters first. That should be simple and easy to read.
Then if that passes, split the string into an array of each character, loop over it, and check counts for each character. Something like Lodash would help with the latter, but you could write it in plain javascript too.
if (/^[a-zA-Z][0-9]$/.test(password)) {
const chars = password.split('');
const counts = {};
chars.forEach(char => {
if (counts[char] && counts[char] > 5) {
isValid = false;
} else {
counts[char] = counts[char] ? counts[char] + 1 : 1;
}
});
return isValid;
}
if i run, validation just can be work only on symbol "/", if I input the other symbol except / didnt working. I'm not use regex.
if(nama!==""){
var i;
var list = new Array ("/","!", "#", "#","$","%","%","^","&","*",
"(",")","_","+","=","-","`","~",";","<",
">",".","?","[","]","{","}",",");
var llength = list.length;
for(i=0; i<llength; i++)
{
if(nama.match(list[i]))
{
alert("Full Name must not contain any number and symbol");
return false;
}
else
{
return true;
}
}
}
There seem to be several problems here. One is that you are calling return true as soon as you reach a valid character. That means that you'll never check anything else if the first letter is valid.
Another problem is that you are trying to check for invalid characters, but how can you know you've checked them all?
A better approach to the whole problem might be to only a list of valid letters; The changes to your original could might be something like the following:
var list = new Array ("a", "A", "b", "B", ... [etc] );
for(i=0; i<llength; i++)
{
if(!nama.match(list[i]))
{
alert("Full Name can only contain letters a-z!");
return false;
}
}
This should only quit the loop (and the containing function) when an invalid character is encountered.
I want to validate following text using regular expressions
integer(1..any)/'fs' or 'sf'/ + or - /integer(1..any)/(h) or (m) or (d)
samples :
1) 8fs+60h
2) 10sf-30m
3) 2fs+3h
3) 15sf-20m
i tried with this
function checkRegx(str,id){
var arr = strSplit(str);
var regx_FS =/\wFS\w|\d{0,9}\d[hmd]/gi;
for (var i in arr){
var str_ = arr[i];
console.log(str_);
var is_ok = str_.match(regx_FS);
var err_pos = str_.search(regx_FS);
if(is_ok){
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
}else{
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
but it is not working
please can any one help me to make this correct
This should do it:
/^[1-9]\d*(?:fs|sf)[-+][1-9]\d*[hmd]$/i
You were close, but you seem to be missing some basic regex comprehension.
First of all, the ^ and $ just make sure you're matching the entire string. Otherwise any junk before or after will count as valid.
The formation [1-9]\d* allows for any integer from 1 upwards (and any number of digits long).
(?:fs|sf) is an alternation (the ?: is to make the group non-capturing) to allow for both options.
[-+] and [hmd] are character classes allowing to match any one of the characters in there.
That final i allows the letters to be lowercase or uppercase.
I don't see how the expression you tried relates anyhow to the description you gave us. What you want is
/\d+(fs|sf)[+-]\d+[hmd]/
Since you seem to know a bit about regular expressions I won't give a step-by-step explanation :-)
If you need exclude zero from the "integer" matches, use [1-9]\d* instead. Not sure whether by "(1..any)" you meant the number of digits or the number itself.
Looking on the code, you
should not use for in enumerations on arrays
will need string start and end anchors to check whether _str exactly matches the regex (instead of only some part)
don't need the global flag on the regex
rather might use the RegExp test method than match - you don't need a result string but only whether it did match or not
are not using the err_pos variable anywhere, and it hardly will work with search
function checkRegx(str, id) {
var arr = strSplit(str);
var regx_FS = /^\d+(fs|sf)[+-]\d+[hmd]$/i;
for (var i=0; i<arr.length; i++) {
var str = arr[i];
console.log(str);
if (regx_FS.test(str) {
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
} else {
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
Btw, it would be better to separate the validation (regex, array split, iteration) from the output (id, jQuery, logs) into two functions.
Try something like this:
/^\d+(?:fs|sf)[-+]\d+[hmd]$/i
Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox
How to check if the number of open braces is equal to the number of close braces using regular expressions?
Here is the code:
var expression1 = "count(machineId)+count(toolId)";
var expression2 = "count(machineId)+count(toolId))";
These are the 2 expressions, where in the expression1, the number of open brackets is equal to number of close brackets and in expression2, the number of open brackets is not equal to number of close brackets. I need a regular expression which counts the number of open brackets and close brackets and gives me the alert. I need to check for valid syntax too.
if(expression1.......){ // here goes the regular expression
alert("Matched");
}
else{
alert("Not matched");
}
var expression1 = "count(machineId)+count(toolId)";
var expression2 = "count(machineId)+count(toolId))";
if (matches(expression1)) {
alert("Matched"); // Triggered!
}
else {
alert("Not matched");
}
if (matches(expression2)) {
alert("Matched");
}
else {
alert("Not matched"); // Triggered!
}
function matches(str) {
try {
new Function(str);
return true;
}
catch (e) {
return !(e instanceof SyntaxError);
}
}
This works because new Function() will cause a syntax error if your code is wrong. Catching the error means you can handle it safely and do whatever you want. Another good thing is that it doesn't execute the code, it just parses it. Basically, you're leveraging your task to the browser's parser.
It doesn't use regex, but it does check if your code is valid. Thus, it tells you if the parentheses match.
Task can be simply solved without regexp, just count braces.
var a = 'count(machineId)+count())toolId)'
var braces = 0;
for (var i=0, len=a.length; i<len; ++i) {
switch(a[i]) {
case '(' :
++braces;
break;
case ')' :
--braces;
break;
}
if (braces < 0) {
alert('error');
break;
}
}
if (braces)
alert('error');
If your goal is to check if an expression is valid (it also means its substring that contains only brackets forms a correct bracket sequence), then regexps won't help you.
Regular expressions can only handle so called "regular languages" (though JS regexps maybe somewhat more powerful than their theoretic counterparts, the price of such power is greater complexity) while language of correct bracket sequences isn't regular.
See those slides — they can give you a glimpse into why regular expressions cannot recognize correct bracket sequence.
Nevertheless, the problem isn't so hard. You should just maintain a stack and go over your string from the left to the right. Every time you meet an opening bracket, you push it to the stack. When you meet a closing bracket, you pop top element of the stack and check if its type matches your one (yes, this algorithm can handle brackets of multiple types). At the end you should just check if the stack is empty.
In case you don't need to handle different types of brackets (you have only '(' and ')', for example) you can just maintain a variable openBrackets (essentially it would represent stack's size) and don't let it become negative.
if (expression1.match(/\(/g).length === expression2.match(/\)/g).length) {
// is equal
}
In order to make it work with strings containing no braces, you may use the following workaround:
((expression1.match(/\(/g) || []).length
If you only care about the count why don't you try something like this.
if(expression1.split('(').length == expression1.split(')').length) {
alert('matched');
}
Here's another way to do it:
function validParenNesting(text) {
var re = /\([^()]*\)/g; // Match innermost matching pair.
// Strip out matching pairs from the inside out.
while (text.match(re))
text = text.replace(re, '');
// If there are any parens left then no good
if (text.match(/[()]/))
return false;
// Otherwise all parens part of matching pair.
return true;
}
"I need to match the no of open braces equal to no of close braces using regular expression"
"I need to check for the valid syntax too."
If 2 is true, then 1 is also true. So, look for matches for what you know is valid syntax -- in this case: {}. Execute a loop which removes all valid matches from the "stack" until there are no valid matches left. If what's left at the end is nothing, then it means your argument is 100% valid. If what's left at the end is something -- it means the "remainders" didn't pass your validity test, and are thus invalid:
var foo = function(str) {
while(str.match(/{}/g)) // loop while matches of "{}" are found
str = str.replace(/{}/g, ''); // "slices" matches out of the "stack"
return !str.match(/({|})/g); // `false` if invalids remain, otherwise `true`
};
foo('{{{}}}'); // true
foo('{{}}}}}}}}}}{}'); // false
Try ...
function matchBraces(s) {
return s.match(/\(/g).length === s.match(/\)/g).length;
}
... then, your code for the alerts would be as follows ...
if(matchBraces(expression1)) {
alert("Matched");
} else {
alert("Not matched");
}
Working copy: jsFiddle
The following can be applied to find the number of brackets.
However, it does not use RegExp and uses simple logic.
var l = 0;
var r = 0;
//Count the number of brackets.
for(var i=0;i<str.length;i++){
if(str[i]=="("){
l++;
}
else if(str[i]==")"){
r++;
}
}
if(l==r){ //The number of opening and closing brackets are equal.
doSomething();
}