Understanding what goes on with 'split()' method
const text = "John is a talented jr. dev. All jr. devs will eventually become software engineers with enough experience.";
const newText = text.split("jr. dev").join("software engineer");
console.log(newText);
split()
: Thesplit()
method is a string method that takes a separator as an argument and splits the string into an array of substrings based on the separator. In the example, we use "jr. dev" as the separator:
const newText = text.split("jr. dev")
const splittedText = text.split("jr. dev");
After this line of code, splittedText
will be an array:
["John is a talented ", ". All ", "s will eventually become software engineers with enough experience."]
Notice how the string is divided into substrings at the positions where "jr. dev" appeared, effectively removing "jr. dev" from the original text.
join()
: Thejoin()
method is an array method that takes a separator as an argument and concatenates all the elements in the array into a single string, inserting the separator between each element. In the example, we use "software engineer" as the separator:const newText = splittedText.join("software engineer");
After this line of code,
newText
will be a single string:"John is a talented software engineer. All software engineers will eventually become software engineers with enough experience."
By using
split()
to create an array of substrings and thenjoin()
to combine those substrings with a new separator, we effectively replace all occurrences of "jr. dev" with "software engineer" in the original string.