find the match at end of the string using regex in javascript - javascript

I have a string for ex "adlkup.db.com" and I want to validate the string for ".com" at the end of the string.
var x = "adlkup.db.com";
So I am trying something like
/.com$/.test(x)
and the . is interpreting to some other regex which finds a single character, except newline or line terminator

A period in a regular expression matches any character.
To make it literal, you need to escape it:
/\.com$/.test('stackoverflow.com'); // true
/\.com$/.test('stackoverflowcom'); // false
Alternatively, as Racil Hilan points out in the comments, you can also use the .lastIndexOf() method in order to check:
var string = 'stackoverflow.com';
string.lastIndexOf('.com') === string.length - 4; // true
or using the .substr() method:
'stackoverflow.com'.substr(-4) === '.com'; // true

In ECMAScript 6 this is done with endsWith:
x.endsWith(".com");
There is a polyfill for old browsers.

After reading your comments, I think you can use this better than the regex:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
document.write(value1 + " " + endWithCom(value1) + "<br/>");
document.write(value2 + " " + endWithCom(value2) + "<br/>");
document.write(value3 + " " + endWithCom(value3) + "<br/>");
function endWithCom(text){
if(text.length < 5)
return false;
return (text.substr(-4) == ".com");
}
And you can easily convert it to generic function so you can pass it any ending you want to check:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
var value4 = "adlkup.db.org";
document.write(value1 + " " + endWithButNotEqual(value1, ".com") + "<br/>");
document.write(value2 + " " + endWithButNotEqual(value2, ".com") + "<br/>");
document.write(value3 + " " + endWithButNotEqual(value3, ".com") + "<br/>");
document.write(value4 + " " + endWithButNotEqual(value4, ".org") + "<br/>");
function endWithButNotEqual(text, ending){
if(text.length <= ending.length)
return false;
return (text.substr(-ending.length) == ending);
}

Related

Adding new line after bracket

I am proxying the function console.log to add some information to my logs and I am as well checking whether the information being logged is an object. I do this to avoid getting a log entry of the sort
2016-12-17 (22:12:51) > [object Object]
Code works fine when passing arguments that are not objects. For example, the command
console.log("hello","world");
prints
2016-12-17 (22:23:53) > hello
2016-12-17 (22:23:53) > world
But if I pass an object as well, the code will fail to insert a new line after the object. For example, the command
console.log("hello",{world:true,hello:{amount:1,text:"hello"}},"world");
prints
2016-12-17 (22:27:32) > hello
2016-12-17 (22:27:32) > { world: true, hello: { amount: 1, text: hello } } 2016-12-17 (22:27:33) > world
(note the missing line break after displaying the object).
Code
JQuery 3.1.1
main.js:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);
I'm not fully understanding objective but what about something along the lines of the following oversimplified override:
var oldLog = console.log;
console.log= function(){
var d= new Date(),
dateString = // process string
.....
for(var i = 0; i<arguments.length; i++){
oldLog(dateString, arguments[i]);
}
}
TL;DR change the iterator variables so they don't share name, or add a "var" to the loop definition to make sure they don't escape your desired scope.
It turns out that the for loops from (my own) console.log and displayArg were "sharing" the value of the iterator i. This is because by not declaring the iterator variable, the scope was broader than what I needed. To clarify, look at this example:
console.log({isThis:"real life"},"hello","world")
The code from console.log will add a date to the beginning of result[0] and then call displayArg(arguments[0]), arguments[0] being {isThis:"real life"}. That function, will iterate over the objects properties, thus i will be assigned the value isThis. After the function returns, the value of i will not go back to 0. Instead, i will be isThis and as a consequence, the line
result[i] += "\n";
translates to
result[isThis] += "\n"
instead of
result[0] += "\n"
Probably the most sensible solution was to add a var in the for declaration of the iterators. The following code works as expected:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (var i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (var i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);

How to concatenate strings without using eval?

How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.
function getLesson() {
var lesson = "lesson" + localStorage.lessonNGS;
document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
document.getElementById("lessonScore").src = (eval(lesson + "." + score));
document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
document.getElementById("lessonTrack").load();
}
This works but I'm told it will cause me conflicts in some browsers.
Simply remove the eval
// Demo data
localStorage.setItem("lessonNGS",1);
var lesson1 = {
number: "1",
title: "Quarter Notes",
score: "scores/01_quarternotes.jpg",
trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};
function getLesson() {
debugger;
var lesson = window["lesson" + localStorage.lessonNGS];
document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
document.getElementById("lessonTitle").innerHTML = lesson.title;
document.getElementById("lessonScore").src = lesson.score;
document.getElementById("mp3").src = lesson.trackmp3;
document.getElementById("ogg").src = lesson.trackogg;
document.getElementById("lessonTrack").load();
}
Javascript String.prototype.concat():
str.concat(string2, string3[, ..., stringN])
Example:
var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));

I need this code to check for digits only

var tel = "123457890";
if (tel.length != 10) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}
Everything about this works for me except I can't get it to check for digits only. When I troubleshoot it with suggestions and run it through http://repl.it/languages/JavaScript I run into error messages.
i.e. When I put a "w" in with a string of 10 numerical digits I want it to return "Sorry, incorrect format" as if I had put in the wrong amount of numbers, etc.
You can use regex:
var tel = "123457890";
if (!tel.match(/^\d{10}$/)) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}
Here's a fiddle:
http://jsfiddle.net/e1qq659g/
Here's a regex pattern:
http://regexr.com/3b77b
var regularExpression = /\d{10}/g;
(tel.match(regularExpression)) ? alert("All digits!") : alert("Not Digits!");
this will match the expression to the string in variable tel - if it does match it alerts "All Digits" - if it does not match it alerts "Not Digits!"
This works. It deletes all letters and checks if the length changes
var tel = "1234567890";
if (tel.length !== 10 || tel.length !== parseInt(tel).toString().length) {
document.write("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
document.write("(" + areaCode + ") " + prefix + "-" + suffix);
}
You can use RegExp both to check if it only contains digits and to extract each part:
var tel = document.getElementById("tel");
var result = document.getElementById("result");
tel.oninput = function(e){
//var match = tel.value.match(/^(\d{3})(\d{3})(\d{4})$/); // Basic RegExp
var match = tel.value
.replace(/\s/g, '') // Removing spaces before RegExp makes it simplier
.match(/^(\d{3}|\(\d{3}\))(\d{3})\-?(\d{4})$/);
if(match == null) {
result.innerHTML = "Sorry, incorrect format.";
return false;
}
// parseInt is optional
var areaCode = parseInt(match[1].replace(/[\(\)]/g,'')); // Just need this with the second RegExp
var prefix = parseInt(match[2]);
var subfix = parseInt(match[3]);
result.innerHTML = "Valida input: (" + areaCode + ") " + prefix + "-" + subfix + "\n"
+ "\n\tArea Code: " + areaCode
+ "\n\tPrefix: " + prefix
+ "\n\tSubfix: " + subfix
};
<input type="text" id="tel" placeholder="Enter a valid phone number"/>
<pre id="result"></pre>
This way you could change the RegExp to make that match a formatted input too, lets say (123)456-7890, (123) 456-7890, (123) 456 - 7890, (123)4567890... that's what the current code does.
If you comment the current RegExp and uncomment the first one it will work just as you was asking for, accepting only a 10 digit input.

JavaScript String Troubles

I've got a set of checkboxes that, when checked, should populate the associated points on a map.
This works great:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
if ( $("#divType1").is(':checked')) searchType += "1,";
if ( $("#divType2").is(':checked')) searchType += "2,";
if ( $("#divType3").is(':checked')) searchType += "3,";
if ( $("#divType4").is(':checked')) searchType += "4,";
whereClause += " AND " + searchType.slice(0, searchType.length - 1) + ")";
But this doesn't:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
if ( $("#divType1").is(':checked')) searchType += "Arbys,";
if ( $("#divType2").is(':checked')) searchType += "Burgerking,";
if ( $("#divType3").is(':checked')) searchType += "Checkers,";
if ( $("#divType4").is(':checked')) searchType += "Dairyqueen,";
whereClause += " AND " + searchType.slice(0, searchType.length - 1) + ")";
Changing "Arbys" to "a" (and so on) also doesn't work, so it's not about the number of characters. I've also tried putting in a set of single quotes around the string that doesn't include the comma. (Sadly, just using the numbers isn't an option for other, unrelated reasons.)
You probably want to use substring instead of slice. slice is for arrays, not for strings.
At all, your solution is very hacky. You should build the query not on client side. Apart of this, the following code may be better solution for you:
var type_column = "FastFood";
var whereClause = [];
if ( $("#divType1").is(':checked')) whereClause.push("Arbys");
if ( $("#divType2").is(':checked')) whereClause.push("Burgerking");
if ( $("#divType3").is(':checked')) whereClause.push("Checkers");
if ( $("#divType4").is(':checked')) whereClause.push("Dairyqueen");
whereClause += " AND " + type_column + " IN ('" + whereClause.join('\',\'') + "')";
You might want to add the search strings to an array. That way you dont need to worry about having a string like "Arbys," with a comma at the end and then stripping the last character, instead you can join the array using the comma as a delimiter:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
var search_array = [];
if ( $("#divType1").is(':checked')) searchArray.push("Arbys");
if ( $("#divType2").is(':checked')) searchArray.push("Burgerking");
if ( $("#divType3").is(':checked')) searchArray.push("Checkers");
if ( $("#divType4").is(':checked')) searchArray.push("Dairyqueen");
whereClause += " AND " + searchType + searchArray.join(',') + ")";

indexOf match variable in this particular case

I want to check if mydiv have or don't have a class, if it don't have it, add whatever it is inside the var newClass. I am attempting to do it like this, but it is not working:
var newClass="classToBeAdded";
if(document.getElementById("mydiv").className.indexOf(/(?:^| )(newClass)(?:$| )/)==-1){
document.getElementById("mydiv").className+=" "+newClass;
}
Use this:
var newClass = "classToBeAdded";
var d = document.getElementById("mydiv");
var r = new RegExp(" " + newClass + " ");
if (r.test(" " + d.className + " "))
// do something here
Or, similarly:
var d = document.getElementById("mydiv");
if ((" " + d.className + " ").indexOf(" " + newClass + " ") != -1)
// do something here
The spaces are added before and after the className string so that we'll match the target class no matter where it appears in the string.
Some tests
Assume the following function:
function hasClass(str, name) {
return (" " + str + " ").indexOf(" " + name + " ") != -1;
}
Tests:
hasClass("target", "target") // true
hasClass("test target test1", "target") // true
hasClass("test1 target", "target") // true
hasClass("target test1", "target") // true
hasClass("test1", "target") // false
You can use javascript property of dom element
document.getElementById("mydiv").classList
it returns array of assigned class names
You should probably use a library to abstract these kind of issues for you.
The rule of thumb is you should focus on your domain specific problems rather than re-inventing the wheel.
jQuery .hassClass is a good candidate

Categories

Resources