I am trying to validate a string only if its first 5 characters are numeric and last 5 characters are letters:
What I have tried:
var userId = "12345abcde";
// Get First and Second Five Characters
var firstFive = userId.substring(0, 5);
var secondFive = userId.substring(5, 10);
// get Global Letter and Nummers
var aStr = /[a-z, A-Z]/g;
var aNum = /[0-9]/g;
var c = userId.match(aNum);
// Try firstFive first...
if (firstFive === c) {
alert('yes');
} else {
alert('nop');
}
This alerts nop.
Is this because firstFive is string and c is object? Where is the error in my thinking?
Live example: http://jsfiddle.net/xe71dd59/1/
Any tips?
Thanks in advance!
Try
/^[0-9]{5}.*[a-z]{5}$/i.test("12345abcde")
match returns an array of results or NULL if none were found.
var c = firstFive.match(aNum);
if(c!=null)
{
if(c.length==5)
{
alert("Yes");
}
}
Try to do this way:
var userId = "12345abcde";
var result = /^[0-9]{5}.*[a-z]{5}$/i.test(userId);
if (result) {
alert('yes');
}else{
alert('nop');
}
Related
I really need your help,
I’d like to make a function so as to validate (return valid or invalid) that the following string below (represented by the var x) has values after each of the 7 dashes
var x = 4-D-5240-P43-120-08A2-8123-0000 (valid)
Some examples below of strings where x is invalid)
var x = 4--5220--120-08C2-8072- (invalid)
var x = 4--5217-P41-120--8072- (invalid)
var x = --5217-P41---8072- (invalid)
I've tried the following, but errors when there is no value:
function test() {
var str1 = "4-D-5240-P43-120-08A2-8123-0000" //works
str1 = str.split('-')
var str = "4--5240-P43--08A2-8123-0000" //error here <--
str = str.split('-')
if (str.length < 8) { alert('validation failed') }
else { alert('validation passed!') }
}
Have you considered Regex?
const
pattern = /(([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+))/,
strs = ["4-D-5240-P43-120-08A2-8123-0000", "4--5217-P41-120--8072-", "--5217-P41---8072-", "4--5220--120-08C2-8072-"];
strs.forEach((str) => {
console.log(`${str} is valid: ${ pattern.test(str) }`);
});
You can try something like this using regex.
var regex1 = /[0-9|a-z][-][0-9|a-z]/g;
var str = "4--5220--120-08C2-8072-";
var str1 = "4-D-5240-P43-120-08A2-8123-0000"
if(str.match(regex1).length== 4) {
alert("match");
}
else
{
alert("no match");
}
if(str1.match(regex1).length== 4) {
alert("match");
}
else
{
alert("no match");
}
So for 1st declared the code and data-target "-"
var id= "100-2-8-8-8-8-8ssss80-0";
var arr = id.split("-");
1st step of checking if code is valid or no. Of we will have less or more than 7 dashes output will be invalid otherwise function will run anouther function to check if we have dashes in right place.
function countDash(){
if (arr.length ==8){
result();
}
else{
alert("invalid");
}
}
After we split our function we need to check if every value of array have a value. If dash will be 1st,last or multicharacter we will get empty value.
function check(value){
return value.length<1;
}
Now we use function that we declarete before to check every value of array. So if array will be empty we will have output invalid otherwise code will be valid
function result(){
if(arr.some(check)){
alert("invalid");
}
else{
alert("valid");
}
}
Finally we need to run 1st function.
window.onload= countDash ;
I hope I explain you well how it goes. If there is something else to do just let me know.
I am trying to use Regex to test if a certain string contains only sets of four non-duplicate characters.
For example I would like to test string
acbdbcaddacb
which would return true as it can return
acbd
bcad
dacb
i.e. sets of four characters which have no duplicates even though the entire string does.
I have tried the following regex which does not work for example and I am not sure why:
/^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1))(?:([a-d])(?!\1))[a-d])+$/
Any solutions?
Thank you
You're close. Your current regex is only checking if the 2nd - 4th letters in each group match the 1st. I believe /^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1|\2))(?:([a-d])(?!\1|\2|\3))[a-d])+$/ should work... or at least it's getting closer to correct I'm not sure if I left out some edge cases but it seems to be working for my test strings
Try this :
function check(str) {
var len = str.length; // check string length
if (len % 4 == 0) { // pass if divided by 4 == true
var arr = str.match(/.{4}/g); // make the in array
var res = [];
for (i = 0; i < arr.length; i++) {
if (arr[i].match(/^(?:([a-zA-Z])(?!.*\1))*$/)) {
res.push(arr[i]); // push if passed regex
}
}
if (arr.length === res.length) { // if they same that means true
console.log("true");
} else {
console.log("false");
}
} else {
console.log("false");
}
}
var str1 = "acbdbcaddacb";
check(str1); // true
var str2 = "aabbccdd";
check(str2); // false
var str3 = "abcde";
check(str3); // false
var str4 = "abcdabcdabcdabcd";
check(str4); // true
var str5 = "abcdabcdabcdabc4";
check(str5); // false
I have two arrays:
enteredCommands = ["valid", "this", 1.1];
validParameters = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
I want to loop through all of the enteredCommands, if it exists in validParameters remove it from validParameters, if it doesn't, break.
I don't know how to compare the regex in this way, if I change validParameters to:
validParameters = ["valid", "alsoValid", /this|that/, /\d+(\.)?\d*/];
and use:
var ok2go = true;
// For each entered command...
for (var i = 0; i < commands.length; i++) {
// Check to see that it is a valid parameter
if (validParameters.indexOf(commands[i]) === -1) {
// If not, an invalid command was entered.
ok2go = false;
break;
// If valid, remove from list of valid parameters so as to prevent duplicates.
} else {
validParameters.splice(validParameters.indexOf(commands[i]), 1);
}
return ok2go;
}
if (ok2go) {
// do stuff if all the commands are valid
} else {
alert("Invalid command");
}
It works the way I want it to for the strings, but obviously not for those values that need to be regex. Is there any way to solve this?
Test cases:
enteredCommands = ["valid", "this", 1.1, 3];
// Expected Result: ok2go = false because 2 digits were entered
enteredCommands = ["valid", "alsoValid", "x"];
// Expected Result: ok2go = false because x was entered
enteredCommands = ["valid", "alsoValid", 1];
// Expected Result: ok2go = true because no invalid commands were found so we can continue on with the rest of the code
You could filter the given commands and if a regular expression match, the exclude it from the regex array. Return only commants which does not match with the rest of the regex array.
function check(array) {
var regex = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
return array.filter(function (a) {
var invalid = true;
regex = regex.filter(function (r) {
if (!r.test(a)) {
return true;
}
invalid = false;
});
invalid && alert('invalid command: ' + a);
return invalid;
});
}
console.log(check(["valid", "this", 1.1, 3])); // 2 digits were entered
console.log(check(["valid", "alsoValid", "x"])); // x was entered
console.log(check(["valid", "alsoValid", 1])); // nothing, no invalid commands were found
I recommend you split up the checks for a matching regex and the check for a matching string.
Conceptually, you might want to do the following (code not tested)
var validStringParameters = ["valid", "alsoValid"];
var validRegexMatches = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
var validCommands = enteredcommands.filter(function(command){
if (validStringParameters.indexOf(command) !== -1){
return true;
}
for (var i = 0; i < validRegexMatches.length; i++){
if (command.test(validRegexMatches[i]){
return true;
})
return false;
}
})
I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ
I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example