Here are a collection of useful JavaScript utility methods. I frequently use these utility methods in my project work and I hope you find them useful as well.
You can suggest any useful JavaScript utility methods in the comment section so that I can add them to this list. For explanation, please refer to comments on each method that would be self-descriptive.
JavaScript Utility Methods
/**
* Parse JSON string or throw error
*/
function parseJSON(data) {
data = data || "";
try {
return JSON.parse(data);
} catch (error) {
throw new Error({
type: 'JSON.parse',
message: error.stack,
reason: error.message
});
}
}
/**
* Safely parse JSON strings (no errors)
*/
function toJSON(data) {
data = data || "";
try {
return JSON.parse(data);
} catch (error) {
return {
type: 'JSON.parse',
message: error.stack,
reason: error.message
};
}
}
/**
* Check empty object
*/
function checkEmptyObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
/**
* Check if the string is empty or null
*/
function checkNotNullAndNotEmpty(data) {
if (data !== null && data !== '') {
return true;
}
return false;
}
/**
* Check if the variable is undefined
*/
function isUndefined(data) {
if (data === "undefined") {
return true;
}
return false;
}
/**
* "Safer" String.toLowerCase()
*/
function lowerCase(str) {
return str.toLowerCase();
}
/**
* "Safer" String.toUpperCase()
*/
function upperCase(str) {
return str.toUpperCase();
}
/**
* UPPERCASE first char of each word.
*/
function properCase(str) {
return lowerCase(str).replace(/^\w|\s\w/g, upperCase);
}
/**
* UPPERCASE first char of each sentence and lowercase other chars.
*/
function sentenceCase(str) {
// Replace first char of each sentence (new line or after '.\s+') to
// UPPERCASE
return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase);
}
/**
* Searches for a given substring
*/
function contains(str, substring, fromIndex) {
return str.indexOf(substring, fromIndex) !== -1;
}
/**
* Escapes a string for insertion into HTML.
*/
function escapeHtml(str) {
str = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
return str;
}
/**
* Unescapes HTML special chars
*/
function unescapeHtml(str) {
str = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, "'")
.replace(/"/g, '"');
return str;
}
/**
* Remove HTML tags from string.
*/
function stripHtmlTags(str) {
return str.replace(/<[^>]*>/g, '');
}
Comments
Post a Comment
Leave Comment