DK-Flag Erik Østergaard - Source code snippets / Kildekode småstykker Go to Home Page
 (Geometric Shapes) Source code snippets Return
  
  
Bottom of This Page

 

JavaScript

- source code snippets /
- kildekode småstykker

Education

 


(Geometric Shapes) JavaScript (JScript) source code snippets JavaScript (JScript) source code snippets / JavaScript (JScript) kildekode småstykker

- JScript is Microsoft's implementation of JavaScript. / - JScript er Microsofts udførelse af JavaScript.

Warning Warning / AdvarselWarning: Don't run the script files without reading them first! /
Warning / AdvarselAdvarsel: Kør ikke script-filerne uden at læse dem først!

JavaScript - source code snippets / JavaScript - kildekode småstykker

Change Case / Store/små bogstaver

Description: This is a collection of functions for use with JavaScript which Change Case of selected western characters in text etcetera among other things 'Sentence case', 'Title Case', and 'Invert (Toggle) Case'. / Beskrivelse: Dette er en samling af funktioner til brug med JavaScript som ændrer Store/små bogstaver af markerede vestlige tegn i tekst og så videre blandt andet 'Første bogstav i sætning med stort', 'Alle ord med stort begyndelsesbogstav' og 'Ombyt store og små bogstaver'.

Overview - Function(s)... / Oversigt - Funktion(er)...

Developed and tested under browser(s): Microsoft Internet Explorer Version 8.x. / Udviklet og testet under browser(e): Microsoft Internet Explorer Version 8.x.

1 Implementation: (How to use:) Insert this code in the <HEAD></HEAD> section of your HTML (HyperText Markup Language) document. /
1 Implementering: (Sådan bruger du:) Indsæt denne kode i <HEAD></HEAD> sektionen af dit HTML (HyperText Markup Language) dokument.



<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript Applet and hide from old browsers -----

var i;                          // Iterator for loops.

var genRandNo;    // Stores Generated random number.

// The RandomNumberGenerator (RNG) with the function 
// 'NextRandomNumber()' and the function 
// 'RandomNumberGenerator()' is an implementation of 
// the Park-Miller algorithm. (See 'Random Number Generators: Good 
// Ones Are Hard to Find', by Stephen K. Park and Keith W. Miller, 
// Communications of the ACM, 31(10):1192-1201, 1988.) The JScript 
// version was written by David N. Smith of IBM's T. J. Watson 
// Research Center. Mr. Smith notes that his version has not been 
// subjected to the rigorous testing required of a mission-critical RNG.

// This RNG is implemented as an object. To use it, you create an 
// instance of the object and then invoke its 'next()' method to 
// return a number. Each call to the 'next()' method returns a new 
// random number. To convert this number to an integer between 
// a lower range number and an upper range number with both numbers 
// included use the function 'random(lrn, urn)'.

// The 'RandomNumberGenerator()' constructor uses the system time, 
// in minutes and seconds, to 'seed' itself, that is, to create the 
// initial values from which it will generate a sequence of numbers. 
// If you are familiar with random number generators, you might have 
// reason to use some other value for the seed. Otherwise, you should 
// probably not change it.

// You might have noticed that JScript's Math object includes 
// a built-in random() method. The version presented here should 
// work as well as, if not better than, the built-in implementations, 
// and will work uniformly on all platforms.

function NextRandomNumber() {
  var hi   = this.seed / this.Q;
  var lo   = this.seed % this.Q;
  var test = this.A * lo - this.R * hi;
  if (test > 0)
    this.seed = test;
  else
    this.seed = test + this.M;
  return (this.seed * this.oneOverM);
}

function RandomNumberGenerator() {
  var d = new Date();
  this.seed = 2345678901 +
    (d.getSeconds() * 0xFFFFFF) +
    (d.getMinutes() * 0xFFFF);
  this.A = 48271;
  this.M = 2147483647;
  this.Q = this.M / this.A;
  this.R = this.M % this.A;
  this.oneOverM = 1.0 / this.M;
  this.next = NextRandomNumber;
  return this;
}

function random(lrn, urn) {
  // Return a generated random number (Integer from 'LowerRangeNumber' and up to 'UpperRangeNumber'; both numbers included).
  // Random LowerRange Number (lrn).
  // Random UpperRange Number (urn).
  // return Math.round((urn - lrn + 1) * rand.next() + lrn);
  return Math.floor((urn - lrn + 1) * rand.next() + lrn);
}

var rand = new RandomNumberGenerator();  // Implement the RandomNumberGenerator (RNG) as an object.
genRandNo = rand.next();  // Generate random number (Fraction between 0 and 1; for example 0.2755983265971 or something similar).
//genRandNo = random(0, 1);  // Generate random number (Integer from 'LowerRangeNumber' and up to 'UpperRangeNumber'; both numbers included).

function doRandomCase(inputString) {
  // This function assumes it's passed a text, and returns
  // the text cased at random.
  var newString = '';
  var sCharacter = '';
  for (var i=0; i<inputString.length; i++) {
    sCharacter = inputString.charAt(i);
    genRandNo = rand.next();  // Generate random number (Fraction between 0 and 1; for example 0.2755983265971 or something similar).
    if ( genRandNo < 0.5 ) {
      newString += sCharacter.toLowerCase();
    } else {
      newString += sCharacter.toUpperCase();
    }
  }
  return (newString);
}

function isWhitespace(ch) {
  // Validates the character passed to the function.
  // Returns a Boolean value - if found: true (1) else false (0).
  //   This Function recognizes these following characters 
  //   as whitespace characters or separators (using the 'escape 
  //   character' - An escape character enables you to output 
  //   characters you wouldn't normally be able to, usually because 
  //   the browser will interpret it differently to what you intended. 
  //   In JavaScript, the backslash (\) is an escape character.):
  //     ' ' : matches space
  //     '\n': matches linefeed
  //     '\r': matches carriage return
  //     '\t': matches horizontal tab
  //     '\f': matches form-feed
  //     '\v': matches vertical tab
  //     '\b': matches backspace
  // Whitespace is usually defined as blank, or space, characters, and 
  // tabs. It may also include carriage returns and linefeeds, as well 
  // as certain other nondisplaying characters.
  // NotInUse: ch == '\v' || 
  if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' ||
      ch == '\b')
    return true;
  return false;
}

function isDelimiter(ch) {
  // Validates the character passed to the function.
  // Returns a Boolean value - if found: true (1) else false (0).
  // Delimiter characters. Common delimiters include commas, forward 
  // or backward slashes, periods, and so on.
  if (ch == ',' || ch == '?' || ch == '-' || ch == '.' ||
      ch == '\\' || ch == '/' || ch == ';' || ch == ':' ||
      ch == '(' || ch == ')' || ch == '|' || ch == '+' ||
      ch == '&' || ch == '%' || ch == '!' || ch == '\"' ||
      ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
      ch == '=' || ch == '<' || ch == '>')
    return true;
  return false;
}

function isDelimiter2(ch) {
  // Validates the character passed to the function.
  // Returns a Boolean value - if found: true (1) else false (0).
  // Delimiter characters. Common delimiters include commas, forward 
  // or backward slashes, periods, and so on.
  if (ch == '!' || ch == '?' || ch == '.')
    return true;
  return false;
}

function isDelimiterNumber(ch) {
  // Validates the character passed to the function.
  // Returns a Boolean value - if found: true (1) else false (0).
  // Delimiter characters. Common delimiters include commas, forward 
  // or backward slashes, periods, and so on.
  ch = "" + ch;  // Force number to a string.
  if (ch == '1' || ch == '2' || ch == '3' || ch == '4' ||
      ch == '5' || ch == '6' || ch == '7' || ch == '8' ||
      ch == '9' || ch == '0')
    return true;
  return false;
}

function doSentenceCase(inputString) {
  // This function assumes it's passed a text, and returns
  // the text sentenced (first character of each selected text
  // sentence upper case and the rest lower case).
  var newString = '';
  var sCharacter = '';
  var sCharacterPrevious = '';
  var sCharacterSecondPrevious = '';
  for (var i=0; i<inputString.length; i++) {
    sCharacter = inputString.charAt(i);
    if ( i == 0 ) {
      newString += sCharacter.toUpperCase();
    } else if ( i == 1 ) {
      sCharacterPrevious = inputString.charAt(i-1);
      if ( isWhitespace(sCharacterPrevious) || isDelimiter2(sCharacterPrevious) ) {
        newString += sCharacter.toUpperCase();
      } else {
        newString += sCharacter.toLowerCase();
      }
    } else {
      sCharacterPrevious = inputString.charAt(i-1);
      sCharacterSecondPrevious = inputString.charAt(i-2);
      if ( isWhitespace(sCharacterPrevious) && sCharacterPrevious != ' ') {
        newString += sCharacter.toUpperCase();
      } else if ( sCharacterPrevious == ' ' && isDelimiter2(sCharacterSecondPrevious) ){
        newString += sCharacter.toUpperCase();
      } else {
        newString += sCharacter.toLowerCase();
      }
    }
  }
  return (newString);
}

function doCapitalize(inputString) {
  // This function assumes it's passed a text, and returns
  // the text capitalized.
  var newString = '';
  var sCharacter = '';
  var sCharacterPrevious = '';
  for (var i=0; i<inputString.length; i++) {
    sCharacter = inputString.charAt(i);
    if ( i == 0 ) {
      newString += sCharacter.toUpperCase();
    } else {
      sCharacterPrevious = inputString.charAt(i-1);
      if ( isWhitespace(sCharacterPrevious) || isDelimiter(sCharacterPrevious) || isDelimiterNumber(sCharacterPrevious) ) {
        newString += sCharacter.toUpperCase();
      } else {
        newString += sCharacter.toLowerCase();
      }
    }
  }
  return (newString);
}

function doInvertCase(inputString) {
  // This function assumes it's passed a text, and returns
  // the text inverted (toggled).
  var newString = '';
  var sCharacter = '';
  for (var i=0; i<inputString.length; i++) {
    sCharacter = inputString.charAt(i);
    if ( sCharacter.toLowerCase() == sCharacter ) {
      newString += sCharacter.toUpperCase();
    } else {
      newString += sCharacter.toLowerCase();
    }
  }
  return (newString);
}

function doReverseString(inputString) {
  // Function to reverse all characters in a string.
  var newString = '';
  for (var i=(inputString.length - 1); i>=0; i--) {
    newString += inputString.charAt(i);
  }
  return (newString);
}

function doReverseString2ndVersion(inputString) {
  // Function to reverse all characters in a string. Second Version.
  var newString = '';
  var sCharacter = '';
  var inword = false;        // Stores state for 'InWord' - Boolean value.
  var word = '';
  var len = inputString.length;
  for (var i = (len - 1); i >= 0; i--) {
    sCharacter = inputString.charAt(i);
    if ( isWhitespace(sCharacter) || isDelimiter(sCharacter) ) {
      if (inword) {
        //alert("Alert 1: " + word); // Only for the purpose of debugging.
        newString += word;
        word = '';
        inword = false;
      }
      newString += sCharacter;
    } else {
      word += sCharacter;
      inword = true;
    }
    if ( (i - 1 == -1) && inword ) {
      //alert("Alert 2: " + word); // Only for the purpose of debugging.
      newString += word;
      word = '';
      inword = false;
    }
  }
  return (newString);
}

function doReverseWords(inputString) {
  // Function to reverse the words in a string.
  var newString = '';
  var sCharacter = '';
  var inword = false;        // Stores state for 'InWord' - Boolean value.
  var word = '';
  var len = inputString.length;
  for (var i = (len - 1); i >= 0; i--) {
    sCharacter = inputString.charAt(i);
    if ( isWhitespace(sCharacter) || isDelimiter(sCharacter) ) {
      if (inword) {
        //alert("Alert 1: " + word); // Only for the purpose of debugging.
        word = doReverseString(word);  // Reverse all characters in a string.
        newString += word;
        word = '';
        inword = false;
      }
      newString += sCharacter;
    } else {
      word += sCharacter;
      inword = true;
    }
    if ( (i - 1 == -1) && inword ) {
      //alert("Alert 2: " + word); // Only for the purpose of debugging.
      word = doReverseString(word);  // Reverse all characters in a string.
      newString += word;
      word = '';
      inword = false;
    }
  }
  return (newString);
}

function doReverseOnlyWords(inputString) {
  // Function to reverse only the words in a string.
  var newString = '';
  var sCharacter = '';
  var inword = false;        // Stores state for 'InWord' - Boolean value.
  var word = '';
  var len = inputString.length;
  for (var i = 0; i < len; i++) {
    sCharacter = inputString.charAt(i);
    if ( isWhitespace(sCharacter) || isDelimiter(sCharacter) ) {
      if (inword) {
        //alert("Alert 1: " + word); // Only for the purpose of debugging.
        word = doReverseString(word);  // Reverse all characters in a string.
        newString += word;
        word = '';
        inword = false;
      }
      newString += sCharacter;
    } else {
      word += sCharacter;
      inword = true;
    }
    if ( (i + 1 == len) && inword ) {
      //alert("Alert 2: " + word); // Only for the purpose of debugging.
      word = doReverseString(word);  // Reverse all characters in a string.
      newString += word;
      word = '';
      inword = false;
    }
  }
  return (newString);
}

function ReplaceString(BigString, NewReplaceString, OldReplaceString) {
  // Replaces the string 'OldReplaceString' through the String 'NewReplaceString' in the String
  // 'BigString'.
  var i;                          // Iterator for loops.
  var OldReplLen;                 // Length of 'OldReplaceString' - Numerical (integer) value.
  var BigLen;                     // Length of 'BigString' - Numerical (integer) value.

  if (NewReplaceString != OldReplaceString) {
    OldReplLen = OldReplaceString.length;
    i = 0;
    while (i != -1) {
      BigLen = BigString.length;
      i = BigString.indexOf(OldReplaceString,i);  // Search down a string from left to right until finding a string fragment matching the specified value. The index of the first character of the matching string is returned.
      if (i != -1) {
        BigString = BigString.substring(0,i) + NewReplaceString + BigString.substring(i + OldReplLen,BigLen);
        i = i + NewReplaceString.length;
      }
    }
  }
  return (BigString);
}

function ReplaceStringExpanded(BigString, NewReplaceString, OldReplaceString, Match_caseBoolean) {
  // Replaces the string 'OldReplaceString' through the String 'NewReplaceString' in the String
  // 'BigString' by finding text having the given pattern of uppercase and lowercase letters by 
  // specifying the search criteria for 'Match_caseBoolean' - a (boolean) numeric value 
  // of numeric '0' (False) or numeric '1' (True) [Default: true].
  var i;                          // Iterator for loops.
  var OldReplLen;                 // Length of 'OldReplaceString' - Numerical (integer) value.
  var BigLen;                     // Length of 'BigString' - Numerical (integer) value.
  var tmpBigStr;                  // Temporary text of 'BigString'.
  var tmpOldReplaceStr;           // Temporary text of 'OldReplaceString'.

  if (Match_caseBoolean == true) {
    // True (1).
    tmpBigStr = BigString;
    tmpOldReplaceStr = OldReplaceString;
  } else {
    // False (0).
    tmpBigStr = BigString.toLowerCase();
    tmpOldReplaceStr = OldReplaceString.toLowerCase();
  }
  if (NewReplaceString != OldReplaceString) {
    OldReplLen = OldReplaceString.length;
    i = 0;
    while (i != -1) {
      BigLen = BigString.length;
      i = tmpBigStr.indexOf(tmpOldReplaceStr,i);  // Search down a string from left to right until finding a string fragment matching the specified value. The index of the first character of the matching string is returned.
      if (i != -1) {
        tmpBigStr = tmpBigStr.substring(0,i) + NewReplaceString + tmpBigStr.substring(i + OldReplLen,BigLen);
        BigString = BigString.substring(0,i) + NewReplaceString + BigString.substring(i + OldReplLen,BigLen);
        i = i + NewReplaceString.length;
      }
    }
  }
  return (BigString);
}

function changeCharInString(inputString, removeChar, insertChar) {
  // Function to change (remove) a character from all places in 
  // a string where it occurs with an other character (or nothing).
  var newString = "";
  for (i=0; i<inputString.length; i++) {
    if ( inputString.charAt(i) != removeChar ) {
      newString += inputString.charAt(i);
    } else {
      newString += insertChar;
    }
  }
  return (newString);
}

function doRemoveExtraInternalSpaces(Text) {
  // This function assumes it's passed a text, and returns
  // the text with extra internal spaces removed.
  var tempTxt = Text;
  while ( (tempTxt.length > 0) && (tempTxt.indexOf("  ",0) != -1) ){
    tempTxt = ReplaceString(tempTxt, " ", "  ");
  }
  return (tempTxt);
}

function doRemoveExtraInternalUnderscores(Text) {
  // This function assumes it's passed a text, and returns
  // the text with extra internal underscores removed.
  var tempTxt = Text;
  while ( (tempTxt.length > 0) && (tempTxt.indexOf("__",0) != -1) ){
    tempTxt = ReplaceString(tempTxt, "_", "__");
  }
  return (tempTxt);
}

// - End of JavaScript code and done hiding -->
</SCRIPT>

Conventions used for: Source code syntax highlighting. / Regler brugt til: Kildekode syntaks fremhævning.

2 Implementation: (How to use:) Now you can call the function name_of_desired_function(desired_function's_parameter(s)) from your project. See also the page mentioned below and see its JavaScript by using View Source. /
2 Implementering: (Sådan bruger du:) Nu kan du kalde funktionen ønskede_funktions_navn(ønskede_funktions_parameter(re)) fra dit projekt. Se også den side, der er nævnt nedenfor og se dens JavaScript ved at bruge Vis Kilde.

You can try the source code here: / Du kan afprøve kildekoden her:

Count Characters / Optæl tegnOpen this link in new window / Åben dette link i nyt vindue

or... / eller...

See similar source code for Basic here: / Se tilsvarende kildekode for Basic her:

[Basic] Change Case / [Basic] Store/små bogstaver

See similar source code for VBA here: / Se tilsvarende kildekode for VBA her:

[VBA] Change Case / [VBA] Store/små bogstaver


(Geometric Shapes) Source code snippetsSource code snippets / Kildekode småstykker

- often included as functions for use in modules with program code, macros, and scripts etcetera. / - mange gange inkluderet som funktioner til brug i moduler med programkode, makroer og scripts og så videre.

The code might need some minor tweaks to run in your application. / Koden kan behøve nogle mindre ændringer for at kunne afvikles i dit anvendelsesområde.

Warning / Advarsel Licence: Free to use, but please share improvements. No warranty - use at own risk. /
Warning / Advarsel Licens: Fri brug, men del venligst forbedringer. Ingen garanti - brug på eget ansvar.

Warning: Don't run the script files without reading them first!
Total absence of any guarantee, warranty, or responsibility for script files, the script(s), the files they may produce, or the effects the script(s) or script-produced files may have. The script(s) is, after all, plain text. The burden is on the person using the script(s) to examine the script source code and determine whether or not a script is usable and safe. Operating systems and browsers are constantly changing. What works today may not work tomorrow!

Advarsel: Kør ikke script-filerne uden at læse dem først!
Totalt fravær af nogen form for garanti, garanti eller ansvar for script-filer, scriptet(scriptene), de filer, de kan producere eller de virkninger, scriptet(scriptene) eller scriptproducerede filer kan have. Scriptet(Scriptene) er, trods alt, almindelig tekst. Byrden er på brugeren af scriptet(scriptene) til at undersøge script kildekoden og afgøre, hvorvidt et script er brugbart og sikkert. Operativsystemer og browsere er under konstant forandring. Hvad fungerer i dag, fungerer muligvis ikke i morgen!


   Top of This Page
   Return
   Go to Home Page