String Prototype Methods

Whole: Whole: Whole:

String.prototype.valueOf()

Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.

String.prototype.toString()

Returns a string representing the specified object. Called automatically when the object is treated as a string, it overrides the Object.prototype.toString() method.

String.prototype.repeat()

Returns a string consisting of the elements of the object repeated the given times.

String.prototype.normalize()

Returns the Unicode Normalization Form of the calling string value.

String.prototype.concat()

Combines the text of two strings and returns a new string.

String.prototype.localeCompare()

Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. (Refer to 8.20 for related information on Intl.)

NFC – Normalization Form Canonical CompositionNFD – Normalization Form Canonical DecompositionNFKC – Normalization Form Compatibility CompositionNFKD – Normalization Form Compatibility Decomposition<br>de – German<br>sv - Swedish
RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "abCDef";
   console.log(s.valueOf()); // abCDef
   console.log(s.toString()); // abCDef
   console.log(s.repeat(2)); // abCDefabCDef
   console.log(s.concat("ghI")); // abCDefghI
      console.log('\u1E9B\u0323'.normalize('NFC')); // ẛ̣
   console.log('\u1E9B\u0323'.normalize('NFD')); // ẛ̣
   console.log('\u1E9B\u0323'.normalize('NFKC')); // ṩ
   console.log('\u1E9B\u0323'.normalize('NFKD')); // ṩ
      console.log(s.localeCompare("abCDef"));  // 0
   console.log('ä'.localeCompare('z', 'de')); // -1
   console.log('ä'.localeCompare('a', 'sv',
                                               { sensitivity: 'base' })); // 1
      var s = 'A\uD835\uDC68';
   var strIter = s[Symbol.iterator]();
   console.log(strIter.next().value); // "A"
   console.log(strIter.next().value); // "\uD835\uDC68"

</script></body><html>

Characters: Characters: Characters: String.prototype.charAt()

Returns the character at the specified index. (also with [])

String.prototype.charCodeAt()

Returns a number indicating the Unicode value of the character at the given index.

String.prototype.codePointAt()

Returns a non-negative integer that is the UTF-16 encoded code point value at the given position.


RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "abc你好吗";
   console.log(s.charAt(3)); // 你
   console.log(s.charCodeAt(1)); // 98
   console.log(s.codePointAt(3)); // 20320

</script></body><html>

Subtring: Subtring: Subtring:

String.prototype.includes()

Determines whether one string may be found within another string.

String.prototype.startsWith()

Determines whether a string begins with the characters of another string.

String.prototype.endsWith()

Determines whether a string ends with the characters of another string.

String.prototype.indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

String.prototype.lastIndexOf()

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

String.prototype.split()

Splits a String object into an array of strings by separating the string into substrings.

String.prototype.slice()

Extracts a section of a string and returns a new string. Negative indices are relative to the end.

String.prototype.substr( from,length )

Returns the characters in a string beginning at the specified location through the specified number of characters.

String.prototype.substring( from,to )

Returns the characters in a string between two indexes into the string.


RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "abCDef";
      console.log(s.includes("CD")); // true
   console.log(s.startsWith("ab")); // true
   console.log(s.endsWith("Def")); // true
   console.log(s.indexOf("C")); // 2
   console.log(s.lastIndexOf("C")); // 2
   console.log(s.split("CD")); // ["ab","ef"]
   console.log(s.split(/[bD]/,2)); // ["a","C"]
      console.log(s.slice(1)); // bCDef
   console.log(s.slice(-4,-2));  // CD
   console.log(s.substr(1)); // bCDef
   console.log(s.substr(1,3)); // bCD
   console.log(s.substring(2)); // CDef
   console.log(s.substring(1,3)); // bC

</script></body><html>

Cases: Cases: Cases:

String.prototype.toLocaleLowerCase()

The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as toLowerCase().(Refer to 8.20 for related information on Intl.)

String.prototype.toLocaleUpperCase()

The characters within a string are converted to an upper case while respecting the current locale. For most languages, this will return the same as toUpperCase().(Refer to 8.20 for related information on Intl.)

String.prototype.toLowerCase()

Returns the calling string value converted to lower case.

String.prototype.toUpperCase()

Returns the calling string value converted to uppercase.

This performs a case-insensitive strings comparison.
RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "Hello World";
    console.log(s.toLowerCase()=="hello world"); // true
   console.log('alphabet'.toLocaleUpperCase());                                                                    // 'ALPHABET'
   console.log('i\u0307'.toLocaleUpperCase('lt-LT')); // 'I'
    console.log('i\u0307'.toLocaleUpperCase(
     ['lt', 'LT', 'lt-LT', 'lt-u-co-phonebk', 'lt-x-lietuva'])); // 'I'

</script></body><html>

Trimming and Padding: Trimming and Padding: Trimming and Padding:

String.prototype.padEnd()  

Pads the current string from the end with a given string to create a new string from a given length.

String.prototype.padStart()  

Pads the current string from the start with a given string to create a new string from a given length.

String.prototype.trim()

Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.

String.prototype.trimLeft()   or String.prototype.trimStart ()  

Trims whitespace from the left side of the string.

String.prototype.trimRight()   or String.prototype.trimEnd ()  

Trims whitespace from the right side of the string.


RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "Hello";
    console.log(s.padStart(8)); //
    Hello
   console.log(s.padEnd(8,"[]")); // Hello[][
   console.log("
  abc
  ".trim()); // abc
   console.log("
  abc
  ".trimLeft()); // abc
   console.log("
  abc
  ".trimEnd()); //
    abc 

</script></body><html>

RegExp: RegExp: RegExp:

More about regular expressions will be explained in 8.19.

String.prototype.replace()

Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

String.prototype.search()

Executes the search for a match between a regular expression and a specified string.

String.prototype.match()

Used to match a regular expression against a string. Results for groups matched are returned as an array.


RESETRUNFULL
<!DOCTYPE html><html><body><script>


   var s = "abCDef";
    console.log(s.replace(/(..)CD/,'$1'));  // abef
   console.log(s.search(/CD/));  // 2
   console.log(s.match(/a/));         // ["a", index: 0, input: "abCDef"]
   console.log(s.match(/(...)(...)/));              // ["abCDef", "abC", "Def", index: 0, input: "abCDef"]

</script></body><html>

<!DOCTYPE html><html><body><script>

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g,function(match,number) {
       return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };}console.log("{0} is dead, but {1} is alive! {0}
                     {2}".format("ASP", "ASP.NET"));// ASP is dead, but ASP.NET is alive! ASP {2}

</script></body><html>

String.prototype.match All ()

Used to match a regular expression against a string. Returns an iterator of all matching results.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

for (const c of "abc".match(/./g)) console.log(c);// a// b// cfor (const e of "abc".matchAll(/./g)) console.log(e);// ["a", "a", index: 0, input: "abc", groups: undefined...]// ["b", "c", index: 0, input: "abc", groups: undefined...]// ["b", "c", index: 0, input: "abc", groups: undefined...]

</script></body><html>

String.prototype.replaceAll(pattern, replacement)

Added in ECMAScript 2021, replaces every occurrence of pattern with replacement, unlike .replace() which (without a /g regular expression) only replaces the first match. If pattern is a RegExp, it must have the global (g) flag set, or a TypeError is thrown.


console.log('2020-01-01'.replace('-', '/'));       // only the first match
console.log('2020-01-01'.replaceAll('-', '/'));
console.log('aAbB'.replaceAll(/a/gi, 'x'));

// console.log('aAbB'.replace(/a/i, 'x'));   // TypeError if a RegExp without /g is passed to replaceAll

2020/01-01 2020/01/01 xxbB

String.prototype.at(index)

Added in ECMAScript 2022 alongside the equivalent Array.prototype.at() (12.2), returns the character at index, counting from the end of the string when index is negative — something the classic [] and .charAt() cannot do directly.


var s = 'JavaScript';
console.log(s.at(0));
console.log(s.at(-1));   // instead of s[s.length - 1] or s.charAt(s.length - 1)
console.log(s[-1]);

J t undefined

String.prototype.isWellFormed() and String.prototype.toWellFormed()

Strings in JavaScript are UTF-16 sequences that can legally contain 'lone surrogates' — a high (or low) surrogate code unit not paired with its matching partner — which are not valid Unicode and cause APIs like encodeURIComponent() or TextEncoder to throw. Added in ECMAScript 2024, .isWellFormed() tests whether a string is free of lone surrogates, and .toWellFormed() returns a copy with every lone surrogate replaced by the replacement character U+FFFD (�).


var lone = 'abc\uD800';   // an unpaired high surrogate
console.log(lone.isWellFormed());
console.log(lone.toWellFormed());

// encodeURIComponent(lone);   // throws URIError
console.log(encodeURIComponent(lone.toWellFormed()));

false abc� abc%EF%BF%BD