Strings
Strings are a fundamental aspect of JavaScript, used extensively in web development for manipulating text. They are objects that represent sequences of characters, and JavaScript provides a multitude of methods for string manipulation. These methods allow developers to perform operations such as searching within a string, transforming string content, extracting substrings, and more. Understanding string methods is crucial for any JavaScript developer, as it enables efficient and effective text processing and manipulation in web applications.
JavaScript string methods are designed to be intuitive and versatile, catering to a wide range of text-related tasks. Whether you’re formatting user input, generating dynamic content, or parsing text data, these methods offer robust solutions. We’ll explore each method, discussing its purpose, usage, and examples, to provide a comprehensive understanding of string manipulation in JavaScript.
Strings Methods Examples
We will now look at the different string methods to see how they could be used practically:
JavaScript String Methods and Examples
charAt()
javascript let greeting = 'Hei, verden!'; console.log(greeting.charAt(5)); // Output: 'v' // This method returns the character at the specified index.
charCodeAt()
javascript let greeting = 'Hei, verden!'; console.log(greeting.charCodeAt(5)); // Output: 118 // Returns the Unicode of the character at the specified index.
concat()
javascript let welcome = 'Hei'; let world = 'verden'; console.log(welcome.concat(', ', world, '!')); // Output: 'Hei, verden!' // Concatenates two or more strings.
includes()
javascript let greeting = 'Hei, verden!'; console.log(greeting.includes('verden')); // Output: true // Checks if a string contains a specified string/characters.
endsWith()
javascript let greeting = 'Hei, verden!'; console.log(greeting.endsWith('!')); // Output: true // Checks if a string ends with specified string/characters.
indexOf()
javascript let greeting = 'Hei, verden!'; console.log(greeting.indexOf('verden')); // Output: 5 // Returns the index of the first occurrence of a specified text in a string.
lastIndexOf()
javascript let repeatedWords = 'Hei, Hei, verden!'; console.log(repeatedWords.lastIndexOf('Hei')); // Output: 5 // Returns the index of the last occurrence of a specified text in a string.
localeCompare()
javascript console.log('å'.localeCompare('z')); // Output: -1 // Compares two strings in the current locale.
match()
javascript let text = 'Besøk Norge!'; let regexp = /[A-Z]/g; console.log(text.match(regexp)); // Output: ['B', 'N'] // Searches a string for a match against a regular expression, and returns the matches.
matchAll()
javascript let iterator = text.matchAll(regexp); for (const match of iterator) { console.log(match); } // Returns an iterator with all matches against a regular expression.
normalize()
javascript let weirdString = '\u004E\u006F\u0308\u0067\u0065'; console.log(weirdString.normalize('NFC')); // Output: 'Nöge' // Normalizes the string into a canonical form.
padEnd()
javascript let day = '5'; console.log(day.padEnd(2, '0')); // Output: '50' // Pads the current string from the end with a given string to create a new string of a specified length.
padStart()
javascript console.log(day.padStart(2, '0')); // Output: '05' // Pads the current string from the start with a given string to create a new string of a specified length.
repeat()
javascript let chorus = 'Ja '; console.log(chorus.repeat(3)); // Output: 'Ja Ja Ja ' // Constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
replace()
javascript let phrase = 'Hei, verden'; console.log(phrase.replace('verden', 'Norge')); // Output: 'Hei, Norge' // Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
replaceAll()
javascript let repeatedPhrase = 'Hei verden, verden er flott!'; console.log(repeatedPhrase.replaceAll('verden', 'Norge')); // Output: 'Hei Norge, Norge er flott!' // Replaces all occurrences of a string with another string.
search()
javascript let phrase = 'Hei, verden'; console.log(phrase.search('verden')); // Output: 5 // Searches a string for a specified value, or regular expression, and returns the position of the match.
slice()
javascript let phrase = 'Hei, verden'; console.log(phrase.slice(0, 3)); // Output: 'Hei' // Extracts a part of a string and returns a new string.
split()
javascript let fruits = 'eple, appelsin, banan'; console.log(fruits.split(', ')); // Output: ['eple', 'appelsin', 'banan'] // Splits a string into an array of substrings.
startsWith()
javascript let phrase = 'Hei, verden'; console.log(phrase.startsWith('Hei')); // Output: true // Checks if a string starts with specified string/characters.
substring()
javascript let phrase = 'Hei, verden'; console.log(phrase.substring(1, 4)); // Output: 'ei,' // Extracts characters from a string between two specified indices.
toLowerCase()
javascript let uppercaseText = 'NORGE'; console.log(uppercaseText.toLowerCase()); // Output: 'norge' // Converts a string to lowercase letters.
toString()
javascript let numberObject = new String(123); console.log(numberObject.toString()); // Output: '123' // Returns the value of a String object.
toUpperCase()
javascript let lowercaseText = 'norge'; console.log(lowercaseText.toUpperCase()); // Output: 'NORGE' // Converts a string to uppercase letters.
trim()
javascript let paddedText = ' Norge '; console.log(paddedText.trim()); // Output: 'Norge' // Removes whitespace from both ends of a string.
trimEnd()
javascript console.log(paddedText.trimEnd()); // Output: ' Norge' // Removes whitespace from the end of a string.
trimStart()
javascript console.log(paddedText.trimStart()); // Output: 'Norge ' // Removes whitespace from the beginning of a string.
valueOf()
javascript console.log(numberObject.valueOf()); // Output: '123' // Returns the primitive value of a String object.
Each of these methods provides a specific functionality that makes handling and manipulating strings in JavaScript more efficient and effective. Understanding and mastering these methods can greatly enhance your capability to work with text data in your web development projects.
Numbers
Introduction to JavaScript Number Methods
JavaScript provides a robust set of methods for manipulating and working with numbers. These are indispensable in web development for tasks like calculations, animations, data analysis, and user input validation. These methods are part of the Number
object and provide functionalities ranging from formatting and conversion to mathematical operations. Understanding these methods is key to efficient and accurate numerical data handling in JavaScript. This lesson will provide a comprehensive overview of the Number methods available in JavaScript, showcasing practical examples and use cases for each method to illustrate their application in real-world scenarios.
JavaScript Number Methods and Examples
toString()
javascript let num = 128; console.log(num.toString(16)); // Output: '80' // Converts a number to a string, optionally using a specified base.
toFixed()
javascript let pi = 3.14159; console.log(pi.toFixed(2)); // Output: '3.14' // Formats a number using fixed-point notation.
toExponential()
javascript console.log(pi.toExponential(2)); // Output: '3.14e+0' // Returns a string representing the number in exponential notation.
toPrecision()
javascript console.log(pi.toPrecision(3)); // Output: '3.14' // Formats a number to a specified length.
valueOf()
javascript let numberObject = new Number(123); console.log(numberObject.valueOf()); // Output: 123 // Returns the primitive value of a Number object.
Number()
javascript console.log(Number('123')); // Output: 123 // Converts a value to a number.
parseInt()
javascript console.log(parseInt('123abc')); // Output: 123 // Parses a string and returns an integer.
parseFloat()
javascript console.log(parseFloat('3.14abc')); // Output: 3.14 // Parses a string and returns a floating point number.
isNaN()
javascript console.log(isNaN('Hello')); // Output: true // Determines whether a value is NaN (Not-a-Number).
isFinite()
javascript console.log(isFinite(2 / 0)); // Output: false // Checks whether a number is finite.
isInteger()
javascript console.log(Number.isInteger(4.2)); // Output: false // Determines whether a value is an integer.
isSafeInteger()
javascript console.log(Number.isSafeInteger(Math.pow(2, 53))); // Output: false // Determines whether a value is a safe integer (within the JavaScript integer range).
EPSILON
javascript console.log(Number.EPSILON); // Output: 2.220446049250313e-16 // Represents the smallest difference between two representable numbers.
MAX_SAFE_INTEGER
javascript console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991 // Represents the maximum safe integer in JavaScript.
MIN_SAFE_INTEGER
javascript console.log(Number.MIN_SAFE_INTEGER); // Output: -9007199254740991 // Represents the minimum safe integer in JavaScript.
MAX_VALUE
javascript console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308 // Represents the largest possible value in JavaScript.
MIN_VALUE
javascript console.log(Number.MIN_VALUE); // Output: 5e-324 // Represents the smallest possible value in JavaScript.
POSITIVE_INFINITY
javascript console.log(Number.POSITIVE_INFINITY); // Output: Infinity // Represents the value of positive infinity.
NEGATIVE_INFINITY
javascript console.log(Number.NEGATIVE_INFINITY); // Output: -Infinity // Represents the value of negative infinity.
Understanding and effectively utilizing these number methods allows for more precise and accurate handling of numerical data in JavaScript. Whether you are dealing with financial calculations, data processing, or simply need to format numbers for display, these methods provide the tools necessary to achieve your goals with efficiency and precision.
Lesson Task
Brief
There are practice questions in the master branch of this repo.
Attempt to answer the questions before checking them against the answers in the answer branch of the repo.