3

Introduction to JavaScript Strings

 2 years ago
source link: https://dev.to/naftalimurgor/introduction-to-javascript-strings-fmb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

JavaScript Strings provide a way of representing and handling characters.

JavaScript Strings

A JavaScript string is a set of character(s) written inside quotes.

// with single quote
let emptyString = '' // an empty string
let name = 'Elon Musk'

// with double quotes
let project = "SpaceX"

Enter fullscreen mode

Exit fullscreen mode

Declaring a String in JavaScript does not restrict usage of single '' and double quotes ""

Acess character

String objects provide a useful method for accessing a character in a string

let catName = 'Anita'
console.log(catName.charAt(0)) // prints 'A', character at a position 0

Enter fullscreen mode

Exit fullscreen mode

Strings behave like Array-like objects, so above can be:

let catName = 'Anita'
console.log(catName[0])// prints 'A'
// looping throug each character
for (let i = 0; i < catName.length; i ++) {
  console.log(catName[i]) // A, n, i, t, a
}

Enter fullscreen mode

Exit fullscreen mode

Get length of a JavaScript String

const THREAD_NAME = 'Moonspiracy'
console.log(THREAD_NAME.length) // prints number of characters// 11

Enter fullscreen mode

Exit fullscreen mode

Summary

JavaScript Strings provide a way of presenting strings using double or single quotes. Both syntaxes are valid and usage is based on project style guide and preferences.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK