Programming Tutorials
var str = "Hello"; str.charAt(0); // H str.charAt(3); // l str.charAt(7); // ""
var str = "Hello world"; str.charCodeAt(0); // 72 because H = 72 str.charCodeAt(6); // 119 because w = 119 // you can now easily change the first character to the next one in the // alphabet using a combination of both functions String.fromCharCode( str.charCodeAt(0) + 1 ); // I
var str = "Hello"; str.toUpperCase(); // HELLO str.charAt(1).toUpperCase() // E
var str = "Hello planet Earth"; var arr1 = str.split(""); // ["H", "e", "l", "l", "o", " ", "p", "l", "a", "n", "e", "t", " ", "E", "a", "r", "t", "h"] var arr2 = str.split(" "); // ["Hello", "planet", "Earth"]
var str = "Hello planet Earth"; var str2 = str.replace("Earth", "Mars"); // Hello planet Mars
var str = "Hello planet Earth"; var part = str.substr(6, 6); // planet
var pattern = /(a|b|c)/giThe pattern above looks for either an a, b, or c character and the g specifies to globally find all matches in a string, not just the first match, and the i specifies the search to be case-insensitive, meaning A, B, or C match the pattern as well. You can view a full list of regular expression examples and keywords here.
/* replace the 'a' character everywhere in string */ var str = "An apple was eaten"; str.replace(/a/gi, "4"); // 4n 4pple w4s e4ten
/* replace all numbers with x's */ var str = "My phone number is 551-555-5555"; str.replace(/[0-9]/gi, "x"); // My phone number is xxx-xxx-xxxx
/* get all words that only start with a letter */ var str = "Hey 4get these words 3_please"; var wor = str.match(/\b[a-z]+/gi); // ["Hey", "these", "words"]
/* find the position in the string where the character A is exactly 2 spaces away from B */ var str = "ABxxAxxB" var pos = str.search(/A..B/gi); // 4
/* get all words that only start with a letter */ var str = "Hey 4get these words 3_please"; var wor = str.match(/\b[a-z]+/gi); // ["Hey", "these", "words"]In the example listed above what is the \b for in the regular expression?
BlindBane
commented on 11/23/16
var str = "ABxxAxxBABxxAxxB"; var pos = str.search(/A..B/gi); console.log(pos); // 4
bLikethat
commented on 06/07/16
hlerickson
commented on 08/30/17
\bsee: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-word-boundary
brycereynolds
commented on 04/09/17
/* get all words that only start with a letter */ var str = "Hey 4get these words 3_please"; var wor = str.match(/\b[a-z]+/gi); // ["Hey", "these", "words"]
JSGary
commented on 12/11/17