User Tools

Site Tools


notes:javascript:strings_in_js

Strings in JavaScript

Extract a substring using substr() and substring():

  • substr(indexStart, length)
  • substring(indexA, indexB)
// Get the last character.
last_char = str.substr(str.length-1, 1);
 
// Get a substring starting from the beginning to the first underscore (excluding).
substr = str.substring(0, str.indexOf('_', 0));
 
// Get a substring starting from the beginning to the last underscore (excluding).<br />
substr = str.substring(0, str.lastIndexOf('_'));
 
// Get a substring starting from the last underscore (excluding) to the end.
substr = str.substring(str.lastIndexOf('_')+1);
 
// Get substring starting from n to the end.
substr = str.substring(n);
 
// Get a substring starting from the first '/' (including) to the end.
substr = str.substring(str.indexOf('/', 0));
 
// Get a substring from the beginning to the one-before-last character (including).
substr = str.substring(0, str.length-1);

Common operations on strings:

// Get the string in lowercase and uppercase.
str_lower = str.toLowerCase();
str_upper = str.toUpperCase();
 
// Replace all occurences of \n with <br />
str = str.replace(/\n/g, '<br />');
 
// Remove a certain character (e.g. '%'):
str = str.replace(/%/g, '');
 
// Get a character from an ASCII code.
str = String.fromCharCode(255);
 
// Capitalize the first character.
str = str.charAt(0).toUpperCase() + str.substr(1);
 
// Trim spaces.
str = str.replace(/^\s*/, '');
str = str.replace(/\s*$/, '');

Return an index of the first non-whitespace character in a string:

  • getFirstNonWhitespace('   abc') returns 3
  • getFirstNonWhitespace('a b c') returns 0
  • getFirstNonWhitespace(' ') returns -1
function getFirstNonWhitespaceIndex(str)
{
    var whitespace = " \t\n\r";
 
    if ((str == null) || (str.length == 0)) return -1;
 
    // Search through string's characters one by one
    // until a non-whitespace character is found.
    for (var i=0; i&lt;str.length; i++)
    {
        var c = str.charAt(i);
        if (whitespace.indexOf(c) == -1) return i;
    }
    return -1;
}
notes/javascript/strings_in_js.txt · Last modified: 2018/01/29 by leszek