Created
August 25, 2012 17:44
-
-
Save jpetto/3468389 to your computer and use it in GitHub Desktop.
JavaScript string methods - 1
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
var name = "Nasir Jones"; | |
// does the name contain 'Mike'? | |
var name_lcase = name.toLowerCase(); // converts string to lower case - easier for comparison | |
console.log(name_lcase); // nasir jones | |
var is_mike = name_lcase.indexOf('mike'); // returns the position of the given string - return -1 if not found | |
console.log(is_mike); // -1 | |
if (is_mike < 0) { | |
name = name.replace("Nasir", "Mike"); // replaces first occurrence of the first string with the second | |
console.log(name); // Mike Jones | |
} | |
var name_parts = name.split(' '); // creates an array by splitting up the string on the given value | |
console.log(name_parts); // ["Mike", "Jones"] <- Array! | |
var first_name = name_parts[0]; // Mike | |
var last_name = name_parts[1]; // Jones | |
console.log(first_name); | |
console.log(last_name); | |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment