Created
January 6, 2012 08:24
-
-
Save psiborg/1569672 to your computer and use it in GitHub Desktop.
JS Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "abcde".charAt(3); // d | |
| "abcde".charCodeAt(0); // 100 = d | |
| String.fromCharCode(100); // d | |
| "abcde".slice(0, 2); // ab | |
| "abcde".slice(1, -1); // bcd | |
| "abcde".slice(-2); // de | |
| "abcde".substr(0, 2); // ab | |
| "abcde".substr(1, 3); // bcd | |
| "abcde".substr(-2); // de | |
| "a,b,c,d,e".split(","); // ["a", "b", "c", "d", "e"] | |
| "a,b,c,d,e".split(",", 3); // ["a", "b", "c"] | |
| "hello world".indexOf("world"); // 6 | |
| "hello world".indexOf("World"); // -1 because it's case-sensitive | |
| "hello world".indexOf("o", 5); // 7 because it skips first o at index 5 | |
| "hello world".lastIndexOf("o"); // 7 | |
| if (myStr.indexOf("hello") !== -1) { | |
| // contains hello | |
| } | |
| "hello world".search(/[aeiou]/); // 1 - find index of first vowel | |
| "hello world".match(/[aeiou]/g); // ["e", "o", "o"] - array of all matches | |
| "(416) 123-4567".replace(/\D/g, ""); // removes non-numeric characters | |
| "Name: Fred".replace(/Name: (\w+)/, "Hello $1"); // Hello Fred | |
| var replaceFn = function (vowel) { | |
| return vowel.toUpperCase(); | |
| } | |
| "hello world".replace(/[aeiou]/g, replaceFn); // hEllO wOrld |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment