Javascript and string functions

JavaScript String Reference

A JavaScript string stores a series of characters like «John Doe».

A string can be any text inside double or single quotes:

String indexes are zero-based:

The first character is in position 0, the second in 1, and so on.

For a tutorial about Strings, read our JavaScript String Tutorial.

String Properties and Methods

Normally, strings like «John Doe», cannot have methods or properties because they are not objects.

But with JavaScript, methods and properties are also available to strings, because JavaScript treats strings as objects when executing methods and properties.

JavaScript String Methods

Name Description
charAt() Returns the character at a specified index (position)
charCodeAt() Returns the Unicode of the character at a specified index
concat() Returns two or more joined strings
constructor Returns the string’s constructor function
endsWith() Returns if a string ends with a specified value
fromCharCode() Returns Unicode values as characters
includes() Returns if a string contains a specified value
indexOf() Returns the index (position) of the first occurrence of a value in a string
lastIndexOf() Returns the index (position) of the last occurrence of a value in a string
length Returns the length of a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a value, or a regular expression, and returns the matches
prototype Allows you to add properties and methods to an object
repeat() Returns a new string with a number of copies of a string
replace() Searches a string for a pattern, and returns a string where the first match is replaced
replaceAll() Searches a string for a pattern and returns a new string where all matches are replaced
search() Searches a string for a value, or regular expression, and returns the index (position) of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts a number of characters from a string, from a start index (position)
substring() Extracts characters from a string, between two specified indices (positions)
toLocaleLowerCase() Returns a string converted to lowercase letters, using the host’s locale
toLocaleUpperCase() Returns a string converted to uppercase letters, using the host’s locale
toLowerCase() Returns a string converted to lowercase letters
toString() Returns a string or a string object as a string
toUpperCase() Returns a string converted to uppercase letters
trim() Returns a string with removed whitespaces
trimEnd() Returns a string with removed whitespaces from the end
trimStart() Returns a string with removed whitespaces from the start
valueOf() Returns the primitive value of a string or a string object
Читайте также:  Css выпадающее меню flexbox

Note

All string methods return a new value.

They do not change the original variable.

String HTML Wrapper Methods

HTML wrapper methods return a string wrapped inside an HTML tag.

These are not standard methods, and may not work as expected.

Method Description
anchor() Displays a string as an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fixed() Displays a string using a fixed-pitch font
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text

Источник

JavaScript String Methods

String search methods are covered in the next chapter.

JavaScript String Length

The length property returns the length of a string:

Example

Extracting String Parts

There are 3 methods for extracting a part of a string:

JavaScript String slice()

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position (end not included).

Example

Slice out a portion of a string from position 7 to position 13:

Note

JavaScript counts positions from zero.

Examples

If you omit the second parameter, the method will slice out the rest of the string:

If a parameter is negative, the position is counted from the end of the string:

This example slices out a portion of a string from position -12 to position -6:

JavaScript String substring()

substring() is similar to slice() .

The difference is that start and end values less than 0 are treated as 0 in substring() .

Example

If you omit the second parameter, substring() will slice out the rest of the string.

JavaScript String substr()

substr() is similar to slice() .

The difference is that the second parameter specifies the length of the extracted part.

Example

If you omit the second parameter, substr() will slice out the rest of the string.

Example

If the first parameter is negative, the position counts from the end of the string.

Example

Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example

Note

The replace() method does not change the string it is called on.

The replace() method returns a new string.

The replace() method replaces only the first match

If you want to replace all matches, use a regular expression with the /g flag set. See examples below.

By default, the replace() method replaces only the first match:

Example

let text = «Please visit Microsoft and Microsoft!»;
let newText = text.replace(«Microsoft», «W3Schools»);

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

Example

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Example

Note

Regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global match):

Example

let text = «Please visit Microsoft and Microsoft!»;
let newText = text.replace(/Microsoft/g, «W3Schools»);

Note

You will learn a lot more about regular expressions in the chapter JavaScript Regular Expressions.

JavaScript String ReplaceAll()

In 2021, JavaScript introduced the string method replaceAll() :

Example

The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.

If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.

Example

Note

replaceAll() is an ES2021 feature.

replaceAll() does not work in Internet Explorer.

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase() :

A string is converted to lower case with toLowerCase() :

JavaScript String toUpperCase()

Example

JavaScript String toLowerCase()

Example

let text1 = «Hello World!»; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to lower

JavaScript String concat()

concat() joins two or more strings:

Example

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

Note

All string methods return a new string. They don’t modify the original string.

Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()

The trim() method removes whitespace from both sides of a string:

Example

JavaScript String trimStart()

ECMAScript 2019 added the String method trimStart() to JavaScript.

The trimStart() method works like trim() , but removes whitespace only from the start of a string.

Example

JavaScript String trimStart() is supported in all modern browsers since January 2020:

JavaScript String trimEnd()

ECMAScript 2019 added the string method trimEnd() to JavaScript.

The trimEnd() method works like trim() , but removes whitespace only from the end of a string.

Example

JavaScript String trimEnd() is supported in all modern browsers since January 2020:

JavaScript String Padding

ECMAScript 2017 added two new string methods to JavaScript: padStart() and padEnd() to support padding at the beginning and at the end of a string.

JavaScript String padStart()

The padStart() method pads a string from the start.

It pads a string with another string (multiple times) until it reaches a given length.

Examples

Pad a string with «0» until it reaches the length 4:

Pad a string with «x» until it reaches the length 4:

Note

The padStart() method is a string method.

To pad a number, convert the number to a string first.

Example

Browser Support

It is supported in all modern browsers:

padStart() is not supported in Internet Explorer.

JavaScript String padEnd()

The padEnd() method pads a string from the end.

It pads a string with another string (multiple times) until it reaches a given length.

Examples

Note

The padEnd() method is a string method.

To pad a number, convert the number to a string first.

Example

Browser Support

It is supported in all modern browsers:

padEnd() is not supported in Internet Explorer.

Extracting String Characters

There are 3 methods for extracting string characters:

JavaScript String charAt()

The charAt() method returns the character at a specified index (position) in a string:

Example

JavaScript String charCodeAt()

The charCodeAt() method returns the unicode of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example

Property Access

ECMAScript 5 (2009) allows property access [ ] on strings:

Example

Note

Property access might be a little unpredictable:

  • It makes strings look like arrays (but they are not)
  • If no character is found, [ ] returns undefined, while charAt() returns an empty string.
  • It is read only. str[0] = «A» gives no error (but does not work!)

Example

Converting a String to an Array

If you want to work with a string as an array, you can convert it to an array.

JavaScript String split()

A string can be converted to an array with the split() method:

Example

text.split(«,») // Split on commas
text.split(» «) // Split on spaces
text.split(«|») // Split on pipe

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is «», the returned array will be an array of single characters:

Example

Complete String Reference

For a complete String reference, go to our:

The reference contains descriptions and examples of all string properties and methods.

Источник

Оцените статью