SaaS Developer   
   About    Testimonials    Contact   

Editing strings with built-in JavaScript methods

While learning some very useful strings methods today, I decided to practice them together with short if-else syntax I discovered yesterday.

  1. This function re-format string begins with capital letter followed by lowercase letters, using toUpperCase and toLowerCase methods:
function toCapitalLetter(string) {
    return (string === '') ? '' : string = string[0].toUpperCase() + string.slice(1).toLowerCase();
  1. This function cuts the end of a string, if it’s longer then the maximum number of symbols, using length and slice methods:
function checkLength(string, maxlength) {
    return (string.length <= maxlength) ? string : string.slice(0 , maxlength-3) + '...';
  1. This function checks, if the phrase contains spam words, using indexOf and toLowerCase methods:
function checkSpam(string) {
    return ( ~string.toLowerCase().indexOf('viagra') || ~string.toLowerCase().indexOf('xxx') ) ? true : false;

You may check all these functions with working examples at JSFiddle or below by clicking “Result”:

comments powered by Disqus