I need to check if test contains at least 2 letters, like SC.
var test='SC129h';
if (test.containsalphabets atleast 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Create a regular expression to match all characters in the string that are in the alphabet, and count them.
var test = "SC129h";
if((test.match(/[A-Za-z]/g).length || 0) >= 2) {
alert("success");
}
Alternatively, to be more efficient, do a linear search and check the ASCII code. This can avoid scanning the whole string.
var test = "SC129h";
var matches = 0;
for(var i = 0; i < test.length; i++) {
if((test[i] >= 'a' && test[i] <= 'z') || (test[i] >= 'A' && test[i] <= 'Z')) {
matches++;
if(matches > 2) break;
}
}
if(matches >= 2) {
// Do something here
}
You should be using the RegEx pattern:
/([A-Za-z])/g
And check for the length of the test to be more than 2.
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match.length >= 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Better Version
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match[1]) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
You can also remove all non alphabetic characters then checking for the length of the result.
'SC129h'.replace(/[^a-z]/gi,'').length > 1
you could do var match = /[a-z]{2,}/gi.test(test) with would return a Boolean
Related
I'm trying to write a function that checks a string for multiple conditions. However, I have reached a wall when trying to figure out how to check if the first character in a string is a letter only.
function SearchingChallenge(str) {
// code goes here
let onlyLetters = /^[a-zA-Z]+$/;
if (str.length > 4 && str.length < 25){
if (onlyLetters.test(str)){
return true;
} else {
return false;
}
} else {
return false;
}
}
"u__adced_123" should return true but it's returning false. I've tried str[0]==onlyLetters but still the same.
onlyLetters.test(str) checks the whole string. To get the first character, use str.charAt(0).
function SearchingChallenge(str) {
let onlyLetters = /^[a-zA-Z]+$/;
if (str.length > 4 && str.length < 25) {
if (onlyLetters.test(str.charAt(0))) {
return true;
} else {
return false;
}
} else {
return false;
}
}
console.log(SearchingChallenge('Hello World!'));
console.log(SearchingChallenge('!dlroW olleH'));
console.log(SearchingChallenge('u__adced_123'));
const SearchingChallenge = str => (
!!str[4] && // > 4
!str[24] && // < 25
(/^[a-z]+$/i).test(str) // alpha
);
// Tests...
// true: greater than four characters
console.log(SearchingChallenge('Fiver'));
// true: less than twenty-five characters
console.log(SearchingChallenge('TwentyFouroooooooooooooo'));
// false: twenty-five or more characters
console.log(SearchingChallenge('TwentyFiveooooooooooooooo'));
// false: contains numbers
console.log(SearchingChallenge('abcd1234'));
// false: less than five characters
console.log(SearchingChallenge('Four'));
I need to pass an array of characters to a function, and extract from that array only letters and numbers; then I should pass those characters to a string and return the string. All of this using a function. I am getting an output warning that the function is not returning the correct value. Say the array was ['A','-','5','/','v','$,'f','4','%','2','3',''], the output should be ths string 'A5vf423'.
I am not sure if I need to declare arrayInput or str but I think the issue is that I am not passing correctly the characters from the vector to the string.
var high = function(arrayInput) {
var str = ' ';
for (var i = 0; i < arrayInput; i++) {
if (arrayInput[i] >= 'a' && arrayInput[i] <= 'a' &&
arrayInput[i] >= 'A' && arrayInput[i] <= 'Z'&&
arrayInput[i] >= '0' && arrayInput[i] <= '9') {
str = arrayInput[i].join('');
}
return str
};
}
EDIT: Solution:
return arrayName.filter(character => /^[a-zA-Z0-9]/.test(character)).join("")
You could use regex to match if is letter or number:
With filter checks each item and check if its letter or number and returns only items that is letter or number.
Regex:
[a-z|0-9] : includes any characters between a-z or 0-9
/i : non case sensitive
const arr = ["A", "/", "r", "6", ".", "a"];
function getString(arr) {
return arr.filter(l => l.match(/[a-z|0-9]/i)).join("")
}
console.log(getString(arr))
Reformat your conditional:
(arrayInput[i]>='a'&&arrayInput[i]<='z'||arrayInput[i]>='A'&&arrayInput[i]<='Z'||arrayInput[i]>='0'&&arrayInput[i]<='9')
Due to operator precedence, the above condition needs no brackets.
function high(arrayInput) {
let str = '';
for (let i = 0; i < arrayInput.length; i++) {
if ((arrayInput[i] >= 'a' && arrayInput[i] <= 'z') ||
(arrayInput[i] >= 'A' && arrayInput[i] <= 'Z') ||
(arrayInput[i] >= '0' && arrayInput[i] <= '9')) {
str += arrayInput[i];
}
}
return str;
}
I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}
I have some words like "Light Purple" and "Dark Red" which are stored as "LightPurple" and "DarkRed". How do I check for the uppercase letters in the word like "LightPurple" and put a space in between the words "Light" and "Purple" to form the word "Light Purple".
thanks in advance for the help
You can use a regex to add a space wherever there is a lowercase letter next to an uppercase one.
Something like this:
"LightPurple".replace(/([a-z])([A-Z])/, '$1 $2')
UPDATE: If you have more than 2 words, then you'll need to use the g flag, to match them all.
"LightPurpleCar".replace(/([a-z])([A-Z])/g, '$1 $2')
UPDATE 2: If are trying to split words like CSVFile, then you might need to use this regex instead:
"CSVFilesAreCool".replace(/([a-zA-Z])([A-Z])([a-z])/g, '$1 $2$3')
Okay, sharing my experience. I have this implement in some other languages too it works superb. For you I just created a javascript version with an example so you try this:
var camelCase = "LightPurple";
var tmp = camelCase[0];
for (i = 1; i < camelCase.length; i++)
{
var hasNextCap = false;
var hasPrevCap = false;
var charValue = camelCase.charCodeAt(i);
if (charValue > 64 && charValue < 91)
{
if (camelCase.length > i + 1)
{
var next_charValue = camelCase.charCodeAt(i + 1);
if (next_charValue > 64 && next_charValue < 91)
hasNextCap = true;
}
if (i - 1 > -1)
{
var prev_charValue = camelCase.charCodeAt(i - 1);
if (prev_charValue > 64 && prev_charValue < 91)
hasPrevCap = true;
}
if (i < camelCase.length-1 &&
(!(hasNextCap && hasPrevCap || hasPrevCap)
|| (hasPrevCap && !hasNextCap)))
tmp += " ";
}
tmp += camelCase[i];
}
Here is the demo.
You could compare each character to a string of uppercase letters.
function splitAtUpperCase(input){
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//start at 1 because 0 is always uppercase
for (var i=1; i<input.length; i++){
if (uppers.indexOf(input.charAt(i)) != -1){
//the uppercase letter is at i
return [input.substring(0,i),input.substring(i,input.length)];
}
}
}
The output is an array with the first and second words.
I think this is definitely not the best way to solve this problem (from an optimization perspective). But it works :)
const createSpacesBetweenWords = (char, index) => {
if (char === char.toUpperCase() && index > 0) {
return ` ${char}`;
}
return char;
};
function formatString(string) {
return string
.split('')
.map(createSpacesBetweenWords)
.join('');
}
formatString('LightPurple'); //returns a new string where words are separated by spaces
In a web application, how do I determine whether the first letter in a given string is upper- or lower-case using JavaScript?
You can use toUpperCase:
if(yourString.charAt(0) === yourString.charAt(0).toUpperCase()) {
//Uppercase!
}
If you're going to be using this on a regular basis, I would suggest putting it in a function on the String prototype, something like this:
String.prototype.isFirstCapital = function() {
return this.charAt(0) === this.charAt(0).toUpperCase();
}
if(yourString.isFirstCapital()) {
//Uppercase!
}
Update (based on comments)
I don't know what you actually want to do in the case that the string does not being with a letter, but a simple solution would be to add a quick check to see if it does or not, and return false if not:
String.prototype.isFirstCapital = function() {
return /^[a-z]/i.test(this) && this.charAt(0) === this.charAt(0).toUpperCase();
}
This will work only with English alphabet.
var ch = myStr.chatAt(0);
if (ch >= 'a' && ch <= 'z') {
// small
} else if (ch >= 'A' && ch <= 'Z') {
// capital
} else {
// not english alphabet char
}
var mystring = "Test string";
var first= "";
if (mystring )
{
first= mystring[1];
}
if (first)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() === $(this).text().charAt(0))
{
alert("Uppercase");
}
});
}
This will be called recursively until a first letter in a string is approached, otherwise returns 'no letters'.
function getFirstCase(string) {
if (string === '') return 'no letters';
var firstChar = string.charAt(0);
/*
* If both lowercase and uppercase
* are equal, it is not a letter
*/
if (firstChar.toLowerCase() === firstChar.toUpperCase()) {
return getFirstCase(string.substr(1));
} else {
return firstChar.toLowerCase() === firstChar ? 'lowercase' : 'uppercase';
}
}
Testing:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
I'm surprised no one's offered a regex solution to this - it seems like the easiest by far:
function getFirstCase(s) {
return (/^[\d\W]*[A-Z]/).test(s) ? 'upper' :
(/^[\d\W]*[a-z]/).test(s) ? 'lower' :
'none';
}
Blatantly stealing #Lapple's test cases:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
// lower upper none upper upper
See http://jsfiddle.net/nrabinowitz/a5cQa/