Javascript useful codes

In time of web development web developers are facing several issues in string , array time loop etc, I am writing some of frequently arrived issues regarding array time loop etc with the approximate solutions.
How to remove a element from an array in JavaScript

First, we have to find the index of the element to remove:

var array = [2, 5, 9, 7];
var index = array.indexOf(9);

we need to use splice

if (index > -1) {
array.splice(index, 1);
}

Foreach loop on an array in JavaScript?

var marray = ["a", "b", "c", "d"];
marray.forEach(function(entry) {
alert(entry);
});

How to check a checkbox using jquery

<input type="checkbox" class="jquerytraining"/>
$('.jquerytraining').prop('checked', true);
$('.jquerytraining').prop('checked', false);

Validate an email address in javascript
use jquery library

function validateValidation(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}

function validate() {
$("#result").text("");
var email = $("#email").val();
if (validateValidation(email)) { $("#resultemail").text(email + " is valid :)"); $("#result").css("color", "green"); } else { $("#result").text(email + " is not valid :("); $("#result").css("color", "red"); } return false; } 
$("#validateemail").bind("click", validate);

<form> <p>Enter an email address:</p> <input id='email'> 
<button type='submit' id='validateemail'>Validate Email</button>
 </form> <h2 id='resultemail'></h2>

How to make first letter of a string uppercase in JavaScript?

function firstLetterCapital(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

In object oriented

String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}

Test now

"hello how are you".capitalize(); => "Hello how are you"

How to get get current URL  in javascript

var URL = window.location.href( Using href);
var URL = window.location.pathname(Using path);

How to get get current URL  in jquery

$(location).attr('href');

Looping in an array in JavaScript

var stringArray= ["Hello","How","are","you"];
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
alert(stringArray[i]);

}

How to check for an empty string in JavaScript?

function isEmpty(str) {
return (!str || 0 === str.length);
}

How to get the current date?

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();

if(dd<10) {
dd = '0'+dd
}

if(mm<10) {
mm = '0'+mm
}

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

Leave comment

Your email address will not be published. Required fields are marked with *.