My Journey to Learning Javascript: Notes- String Manipulation





.Split()


split takes any string and separates said string into an array of substrings. The parameter you give determines where the string is split. Examples:

var lottoNumbers = “1,10,100,1000”

you name a new variable with the previous variable and assign the split method. You assign the parameter where you want to split the numbers.

var newLottoNumbers=lottoNumbers.split(“,”)
this returns[“1”,”10”,”100”,”1000”]

for a better understanding. If i had the same string but instead of (,) they were separated by (+). like so=

var lottoNumbers = “1+10+100+1000”

If i tried to use the same split method as the last example it will not do anything because there is no comma in this string. i would have to use the parameter (+)

var newLottoNumbers = lottoNumbers.split(+)
This will work because the string does indeed contain (+) separating the string items so it will return [“1”,”10”,”100”,”1000”]



.Replace()

Replace method searches a string for the substring you are looking for and replaces that substring with the substring you give it. The syntax for this method is

.substring(substring you’re looking for, subtring to replace it)


Example:

var myThoughts = “Javascript is hard!”

You create a new variable that will receive the new string( var myThoughts will not change)

var newThoughts = myThoughts.replace(“hard” ,”easy”)
*This will replace “hard” with “easy”. When console.log(newThoughts) returns: “Javascript is easy”

You can replace multiple words as well.

var myThoughts = “Javascript is hard!”
var newThoughts = myThoughts.replace(“is hard” ,”isn’t easy”)
*This will return “Javascript isn’t easy!”
*Notice the exclamation mark was not replaced. replace() only replaces what you tell it to.


.Search()

This method will search a string and tell you where it is located in the index. It only needs on parameter, and that is the substring you are searching for. Example:

var favoriteRestaurants = “I like mcdonalds, burgerking, and arby’s”
var favoriteFood= favoriteRestaurants.search(“burger”)
*If i console.log(favoriteFood) it will return 18. Which is the index where “burger” begins. If i tried to search for a substring that was not in the original string console.log(favoriteFood) would return -1.


.Match()

The match() method searches a string for a what you are searching for and returns the matches, as an Array object.

var favoriteNumbers=”My favorite numbers are 8, 9, 21 and 48”
var oneWord=favoriteNumbers.match(“21”)
returns
[“21”]


*Typing in a substring that is not in the string returns null