JavaScript — Things you should know
3 ways to combine strings
JavaScript may very well be the most popular programming language in use today. JavaScript’s ability to create web applications, front-end, back-end, and mobile applications with React Native makes it a dominant gene in the genetic pool of programming languages.
In your web applications, strings will constantly be used in order to bring your app to life. MDN says a string is:
The
String
object is used to represent and manipulate a sequence of characters.Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their
length
, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with theindexOf()
method, or extracting substrings with thesubstring()
method.
There are times when you are going to need to handle text and combine strings. Here are 3 ways to do so!
The +
Operator
This is simple and is super intuitive. The same +
operator you use for adding two numbers can be used to concatenate two strings!
const str = 'My dogs name is' + ' ' + 'Skip';
str; // 'My dogs name is Skip'
This also works with variables”
const phrase = 'My dogs name is'
const name = "Skip"
const output = phrase + " " + nameoutput; // 'My dogs name is Skip'
Template Strings
Template strings are used in a lot of other languages such as Ruby. We use templates to use a technique called string interpolation.
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Template strings create a simple way to include expressions in your string creation that is comprehensible and crisp.
const name = "Skip"
const phrase = `My dogs name is ${name}`phrase; // 'My dogs name is Skip'
join()
The join()
method is very simple to use. Because it’s working with an array, it’s very handy if you want to add additional strings.
The
join()
method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const name = 'Skip';
const phrase = ["My dog name is", name]const output = phrase.join(" ")
output; // 'My dogs name is Skip'