String and Number methods

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

  1. charAt()

    javascript
    	let greeting = 'Hei, verden!';
    	console.log(greeting.charAt(5)); // Output: 'v'
    	// This method returns the character at the specified index.
  2. charCodeAt()

    javascript
    	let greeting = 'Hei, verden!';
    	console.log(greeting.charCodeAt(5)); // Output: 118
    	// Returns the Unicode of the character at the specified index.
  3. concat()

    javascript
    	let welcome = 'Hei';
    	let world = 'verden';
    	console.log(welcome.concat(', ', world, '!')); // Output: 'Hei, verden!'
    	// Concatenates two or more strings.
  4. includes()

    javascript
    	let greeting = 'Hei, verden!';
    	console.log(greeting.includes('verden')); // Output: true
    	// Checks if a string contains a specified string/characters.
  5. endsWith()

    javascript
    	let greeting = 'Hei, verden!';
    	console.log(greeting.endsWith('!')); // Output: true
    	// Checks if a string ends with specified string/characters.
  6. 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.
  7. 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.
  8. localeCompare()

    javascript
    	console.log('å'.localeCompare('z')); // Output: -1
    	// Compares two strings in the current locale.
  9. 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.
  10. 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.
  11. normalize()

    javascript
    	let weirdString = '\u004E\u006F\u0308\u0067\u0065';
    	console.log(weirdString.normalize('NFC')); // Output: 'Nöge'
    	// Normalizes the string into a canonical form.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. split()

    javascript
    	let fruits = 'eple, appelsin, banan';
    	console.log(fruits.split(', ')); // Output: ['eple', 'appelsin', 'banan']
    	// Splits a string into an array of substrings.
  20. startsWith()

    javascript
    	let phrase = 'Hei, verden';
    	console.log(phrase.startsWith('Hei')); // Output: true
    	// Checks if a string starts with specified string/characters.
  21. substring()

    javascript
    	let phrase = 'Hei, verden';
    	console.log(phrase.substring(1, 4)); // Output: 'ei,'
    	// Extracts characters from a string between two specified indices.
  22. toLowerCase()

    javascript
    	let uppercaseText = 'NORGE';
    	console.log(uppercaseText.toLowerCase()); // Output: 'norge'
    	// Converts a string to lowercase letters.
  23. toString()

    javascript
    	let numberObject = new String(123);
    	console.log(numberObject.toString()); // Output: '123'
    	// Returns the value of a String object.
  24. toUpperCase()

    javascript
    	let lowercaseText = 'norge';
    	console.log(lowercaseText.toUpperCase()); // Output: 'NORGE'
    	// Converts a string to uppercase letters.
  25. trim()

    javascript
    	let paddedText = '  Norge  ';
    	console.log(paddedText.trim()); // Output: 'Norge'
    	// Removes whitespace from both ends of a string.
  26. trimEnd()

    javascript
    	console.log(paddedText.trimEnd()); // Output: '  Norge'
    	// Removes whitespace from the end of a string.
  27. trimStart()

    javascript
    	console.log(paddedText.trimStart()); // Output: 'Norge  '
    	// Removes whitespace from the beginning of a string.
  28. 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

  1. toString()

    javascript
    	let num = 128;
    	console.log(num.toString(16)); // Output: '80'
    	// Converts a number to a string, optionally using a specified base.
  2. toFixed()

    javascript
    	let pi = 3.14159;
    	console.log(pi.toFixed(2)); // Output: '3.14'
    	// Formats a number using fixed-point notation.
  3. toExponential()

    javascript
    	console.log(pi.toExponential(2)); // Output: '3.14e+0'
    	// Returns a string representing the number in exponential notation.
  4. toPrecision()

    javascript
    	console.log(pi.toPrecision(3)); // Output: '3.14'
    	// Formats a number to a specified length.
  5. valueOf()

    javascript
    	let numberObject = new Number(123);
    	console.log(numberObject.valueOf()); // Output: 123
    	// Returns the primitive value of a Number object.
  6. Number()

    javascript
    	console.log(Number('123')); // Output: 123
    	// Converts a value to a number.
  7. parseInt()

    javascript
    	console.log(parseInt('123abc')); // Output: 123
    	// Parses a string and returns an integer.
  8. parseFloat()

    javascript
    	console.log(parseFloat('3.14abc')); // Output: 3.14
    	// Parses a string and returns a floating point number.
  9. isNaN()

    javascript
    	console.log(isNaN('Hello')); // Output: true
    	// Determines whether a value is NaN (Not-a-Number).
  10. isFinite()

    javascript
    	console.log(isFinite(2 / 0)); // Output: false
    	// Checks whether a number is finite.
  11. isInteger()

    javascript
    	console.log(Number.isInteger(4.2)); // Output: false
    	// Determines whether a value is an integer.
  12. 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).
  13. EPSILON

    javascript
    	console.log(Number.EPSILON); // Output: 2.220446049250313e-16
    	// Represents the smallest difference between two representable numbers.
  14. MAX_SAFE_INTEGER

    javascript
    	console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
    	// Represents the maximum safe integer in JavaScript.
  15. MIN_SAFE_INTEGER

    javascript
    	console.log(Number.MIN_SAFE_INTEGER); // Output: -9007199254740991
    	// Represents the minimum safe integer in JavaScript.
  16. MAX_VALUE

    javascript
    	console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308
    	// Represents the largest possible value in JavaScript.
  17. MIN_VALUE

    javascript
    	console.log(Number.MIN_VALUE); // Output: 5e-324
    	// Represents the smallest possible value in JavaScript.
  18. POSITIVE_INFINITY

    javascript
    	console.log(Number.POSITIVE_INFINITY); // Output: Infinity
    	// Represents the value of positive infinity.
  19. 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.