javascript for checking alphabets from a string - javascript

I have a string which is of format 245545g65.
var value = "245545g65"
var last3Letters = value.substring(7,9); // abc
Now I want to validate whether the last three letters contains only alphabets, if it is alphabet , i want to alert it.how to alert g?
how do i do this?

assuming that "contains only alphabets" means the last three characters are a combination of the letters a-z:
var str = '245545g65';
if (/[a-z]{3}$/.test(str)){
// last three characters are any combinations of the letters a-z
alert('Only letters at the end!');
}

you can use RegEx and compare length
var re = new RegExp("[^0-9]*", "g");
var newlast3Letters =last3Letters.replace(re,"");
if(newlast3Letters.length!=last3Letters.length)
{
alert("not all alphabets");
}
else
{
alert("all alphabets");
}

you can use isNaN to check weather s string is number
if (!isNan(last3Letters))
alert(last3Letters + ' is number.')
else
alert(last3Letters + ' is not number.')

You can also do this:
var value = "245545g65"
if(value.slice(value.length-3).search(/[^a-z]/) < 0) {
alert("Just alphabets");
} else {
alert("Not just alphabets");
}

Easy:
var alpha = /^[A-z]+$/;
alpha.test(last3Letters);
This will return a boolean (true/false). Stolen from here.

Related

Javascript validate string is a character followed by numbers

I am trying to validate a string where the first character must be an 'x' and the remaining characters must be numerical. For example:
x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;
Here is my code:
function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;
// Debugging
console.log(firstLetter);
console.log(remainingCode);
if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}
I've debugged my isNumeric() function, so I'm 99.9% sure the issue isn't there, but here it is just in case:
function isNumeric(numberIn)
{
var returnValue = true;
if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
{
returnValue = false;
}
return returnValue;
}
I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking if(!(firstLetter == 'x')) I've tried == and ===and I've tried casting the remaining portion of the code with Number() , +() and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.
You can use a regular expression test:
function isValidCode(code) {
return /^[a-z]\d+$/.test(code);
}
I am making an assumption that a lower case letter is required, followed by at least one digit.
To match only only the letter 'x', use:
function isValidCode(code) {
return /^x\d+$/.test(code);
}
You can use RegExp /^x(?=\d+$)/ to match x at beginning of input followed by digits followed by end of input
var arr = ["x1234"
, "k1234"
, "x12k4"
, "1x123"];
var re = /^x(?=\d+$)/;
arr.forEach(function(str) {
console.log(`${str}: ${re.test(str)}`)
})

How can I convert all my user inputs to the upper case letter using JavaScript?

I have a JavaScript function that checks the user input and will compare it against the database.
function checkUserInput() {
var userInput = document.getElementById("textInput").value;
var stringToCheckAgainst = random_images_array[num].split('.');
if (userInput == stringToCheckAgainst[0]) {
document.getElementById("row1").innerHTML = "<p>" + txt.fontsize(5) + "</p>";
document.close();
} else {
//user has inputted an incorrect string
document.getElementById("row1").innerHTML = "<p>" + txt1.fontsize(5) + "</p>";
document.close();
}
}
My problem is at the moment this function is case sensitive which means if the user types in “apple” it will return false statements as a fact that all of my objects are named with uppercase letters.
How can I make my function not case sensitive to works with both lower case and uppercase letters no matter how the user is typing in?
You may use like this:
if (userInput.toUpperCase() == stringToCheckAgainst[0].toUpperCase()) {
Try this:
if(cmp_first.toUpperCase()===cmp_second.toUpperCase()){
alert('Strings are Identical');
}else{
alert('String mismatch');
}
var userInput = document.getElementById("textInput").value;
document.write(userInput.toUpperCase());
To convert a string to lowercase or uppercase letters, use: toLowerCase() and toUpperCase() methods.
var userInput = document.getElementById("textInput").value;
userInput.toLowerCase() // lowercase
userInput.toUpperCase() // UPPERCASE
-Use the toUpperCase() function.
EXAMPLE: Desired_string.toUpperCase

validate numeric with 1 special character

i want to validate numeric and allows the + (plus sign), but its not working
what i want
+63443 -> OK
8452 -> OK
s55sd -> Not OK
here's my code
var Nom = $("#addKonId1").val().split(" ").join("").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if (!intRegex.test(Nom)) {
alert("wrong Number");
} else {
alert(Nom);
}
Try This
var Nom = $("#addKonId1").val().trim(" ");
var intRegex = /^\+?\d+$/;
if(!intRegex.test(Nom)) {
alert("wrong Number");
}
else{
alert(Nom);
}
DEMO HERE
The regular expression for what you're looking for is:
^\+?\d+$
Which means "a string beginning with optionally one plus sign followed by one or more digits".
Your regex right now only tests for a string beginning with one or more digit characters. Alter intRegex like so:
var intRegex = /^\+?\d+$/;
On a side note, what you're doing in your first line with the replacing can simply be done with trim():
var Nom = $("#addKonId1").val().split(" ").join("").trim();

match specific characters in javascript

I have a string from which I want to check if it only contains characters that are allowed.
Allowed are only the letters a, b, c, d, e, k. I thought of something like this:
var string1 = "abcdekabc"
if (string1 contains only a,b,c,d,e,k) {
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
How can I do this? Is there a regex that would help me? Unfortunately I don't have experience with regex.
Yes there is a regexp :
var pattern = new RegExp('[^abcdek]', 'i');
var string1 = "abcdekabc";
if(!pattern.test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
Which can be reduce to :
var string1 = "abcdekabc";
if(!(/[^abcdek]/i).test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
If you prefer, you can go the other way arround (not checking illegal characters) :
var string1 = "abcdekabc";
if((/^[abcdek]+$/i).test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}

Scan string for special characters and alphabets

I have a textbox which accepts time (max of 5 chars) in the format hh:mm or hhmm. Pls tell me a way I can just scan the string entered in the textbox, for special characters and alphabets? [If the string entered has these chars or alphabets, then an alert is displayed('Pls enter a valid time')] I tried the str.match and str.indexOf methods but it doesn't seem to help.
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < 5; i++) {
if (iChars.indexOf(clks.charAt(i)) != -1) {
alert ("Pls enter a valid time");
return false;
}
}
.....}
</script>
How are you using string.match()? This should work:
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
if (clk.match(/[^0-9:]/)) {
alert("Please enter a valid time");
}
// or, an even more precise regex
if (!clk.match(/^\d+:\d+$/)) {
alert("Please enter a valid time");
}
.....}
</script>
The first regex match should check for anything that is NOT a digit or the ':' character, and raise an alert if it finds anything. The second one will match any string that starts with one or more digits, then a ':' character, then one or more digits, then the end of the string (which is the format you're trying to match).

Categories