Tutorial: Javascript String Methods
Tags: javascript, programming, codenewbie
Published: 2022-01-15 09:18:50

---
title: Tutorial: Javascript String Methods
published: True
date: 2021-01-10 01:16:04 UTC
tags: ["JavaScript", "Programming", 'codenewbie']
canonical_url: https://www.devwares.com/blog//javascript-string-methods
---

## JavaScript String Methods

You can use string methods to work with strings.

**String Methods and Properties** Values with no properties or methods, such as "John Doe", are considered primitive (because they are not objects). However, primitive values can use JavaScript methods and properties because JavaScript interprets primitive values as objects when executing methods and properties.

**String Length:** The length attribute returns the string's length.

**JavaScript Code:**

```javascript
var txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var alpha = txt.length;

```

**Finding a String in a String:**

The indexOf() method returns the position of the first occurrence of a string's provided text. JavaScript starts counting at zero. In a string, 0 is the first place, 1 is the second, 2 is the third ...

**JavaScript Code:**

```javascript
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf('locate');

```

The lastIndexOf() method returns the index of a string's last occurrence of a given text:

**JavaScript Code:**

```javascript
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf('locate');

```

If the text cannot be retrieved, both indexOf() and lastIndexOf() return -1. Both methods take a second parameter as the search's starting point:

**JavaScript Code:**

```javascript
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf('locate', 15);

```

The lastIndexOf() method searches backwards (from the end to the beginning), which means that if the second parameter is 15, the search will begin at position 15 and continue until the string reaches the beginning.

**JavaScript Code:**

```javascript
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf('locate', 15);

```

**Searching for a String in a String**

The search() method looks for a provided value in a string and returns the position of the match.

**JavaScript Code:**

```javascript
var str = "Please locate where 'locate' occurs!";
var pos = str.search('locate');

```

Is there a difference between indexOf() and search()? They both take the same arguments (parameters) and produce the same result, right? The two approaches are not equivalent. These are the distinctions:

A second start position argument cannot be passed to the search() method. The indexOf() technique is unable to handle large search values (regular expressions).

**Extracting String Parts**

There are three methods to remove a part of a string:

- slice(start, end)
- substring(start, end)
- substr(start, length)

**The slice() Method**

slice() takes a portion of a string and returns it as a new string. The technique accepts two parameters: the start and end positions (end not included). This example cuts a section of a string from position 7 to position 12 (13-1) as follows:

**JavaScript Code:**

```javascript
var str = 'Apple, Banana, Kiwi';
var res = str.slice(7, 13);

```

The position is counted from the end of the string if a parameter is negative.

**The substring() Method**

substring() is similar to slice().The difference is that substring() cannot accept negative indexes.

**JavaScript Code:**

```javascript
var str = 'Apple, Banana, Kiwi';
var res = str.substring(7, 13);

```

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

**The substr() Method**

slice() is comparable to substr(). The second option, on the other hand, sets the length of the extracted section.

**JavaScript Code:**

```javascript
var str = 'Apple, Banana, Kiwi';
var res = str.substr(7, 6);

```

The result of res will be: Banana Substr() will slice out the rest of the string if the second parameter is omitted.

**JavaScript Code:**

```javascript
var str = 'Apple, Banana, Kiwi';
var res = str.substr(7);

```

The result of res will be Banana, Kiwi If the first parameter is negative, the position counts from the end of the string.

**JavaScript Code:**

```javascript
var str = 'Apple, Banana, Kiwi';
var res = str.substr(-4);

```

The result of res will be: Kiwi

**The concat() Method:**concat() joins two or more strings:

**JavaScript Code:**

```javascript
var text1 = 'Hello';
var text2 = 'World';
var text3 = text1.concat(' ', text2);

```

Instead of using the plus operator, you can use the concat() function. These two lines perform the same function.

**JavaScript Code:**

```javascript
var text = 'Hello' + ' ' + 'World!';
var text = 'Hello'.concat(' ', 'World!');

```

A new string is returned by all string functions. They don't change the original string in any way. Strings are immutable, according to the formal definition: Strings can only be substituted, not modified.

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

**JavaScript Code:**

```javascript
var str = ' Hello World! ';
alert(str.trim());

```

If you need to support IE 8, you can use replace() with a regular expression instead

**JavaScript Code:**

```javascript
var str = ' Hello World! ';
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

```

You can also use the replace solution above to add a trim function to the JavaScript String.prototype:

**JavaScript Code:**

```javascript
if (!String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
var str = ' Hello World! ';
alert(str.trim());

```

**Extracting String Characters**

There are 3 methods for extracting string characters:

- charAt(position)
- charCodeAt(position)
- The charAt() Method

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

**JavaScript Code:**

```javascript
var str = 'HELLO WORLD';
str.charAt(0); // returns H

```

**The charCodeAt() Method**

The unicode of the character at a particular index in a string is returned by the charCodeAt() method: A UTF-16 code is returned by this procedure (an integer between 0 and 65535).

**JavaScript Code:**

```javascript
var str = 'HELLO WORLD';
str.charCodeAt(0); // returns 72

```

**Converting a String to an Array**

The split() method can be used to convert a string to an array: If the separator isn't specified, the returned array will have the entire string at index [0]. The returned array will be an array of single characters if the separator is "":

**JavaScript Code:**

```javascript
var txt = 'a,b,c,d,e'; // String
txt.split(','); // Split on commas
txt.split(' '); // Split on spaces
txt.split('|'); // Split on pipe.

```

[![Contrast Bootstrap UI Kit](https://www.devwares.com/static/6b149e3d75b230f7e8452ace9e21bb05/587b0/banner-ad-1.png "Contrast Bootstrap UI Kit")](https://www.devwares.com/product/bootstrap-contrast-pro)

## Resources

You may find the following resources useful:

- [Get Contrast PRO](https://www.devwares.com/product/contrast-pro)
- [Tailwind 3.0 is finally available. here are all the major](https://www.devwares.com/blog/tailwind-3.0-is-finally-out)
- [Introduction to Javascript](https://www.devwares.com/blog/javascript-tutorial-1)
- [Tutorial: JavaScript This Keyword](https://www.devwares.com/blog/javascript-this-keyword)
- [Tutorial: Sorting In Javascript](https://www.devwares.com/blog/javascript-sort)
- [Contrast Installation](https://www.devwares.com/docs/contrast/react/Installation/)
- [Charts](https://www.devwares.com/docs/contrast/react/chart/)
- [Accordion](https://www.devwares.com/docs/contrast/react/components/accordion/)
- [Alert](https://www.devwares.com/docs/contrast/react/components/alert/)
- [Animation](https://www.devwares.com/docs/contrast/react/components/animations/)
- [Autocomplete](https://www.devwares.com/docs/contrast/react/components/autocomplete/)
- [Badges](https://www.devwares.com/docs/contrast/react/components/badge/)
- [Box](https://www.devwares.com/docs/contrast/react/components/box/)
- [Breadcrumb](https://www.devwares.com/docs/contrast/react/components/breadcrumb/)
- [ButtonGroup](https://www.devwares.com/docs/contrast/react/components/buttonGroup/)
- [ButtonToolbar](https://www.devwares.com/docs/contrast/react/components/buttonToolbar/)
- [Button](https://www.devwares.com/docs/contrast/react/components/buttons/)
- [Card](https://www.devwares.com/docs/contrast/react/components/card/)
- [Carousel](https://www.devwares.com/docs/contrast/react/components/carousel/)
- [Checkbox](https://www.devwares.com/docs/contrast/react/components/checkbox/)
- [Collapse](https://www.devwares.com/docs/contrast/react/components/collapse/)
- [DropDown](https://www.devwares.com/docs/contrast/react/components/dropdown/)
- [Footer](https://www.devwares.com/docs/contrast/react/components/footer/)
- [Icon](https://www.devwares.com/docs/contrast/react/components/icon/)
- [Iframe](https://www.devwares.com/docs/contrast/react/components/iframe/)
- [Input](https://www.devwares.com/docs/contrast/react/components/input/)
- [InputGroup](https://www.devwares.com/docs/contrast/react/components/inputgroup/)
- [ListGroup](https://www.devwares.com/docs/contrast/react/components/listgroup/)
- [Mask](https://www.devwares.com/docs/contrast/react/components/mask/)
- [Modal](https://www.devwares.com/docs/contrast/react/components/modal/)
- [Multiselect](https://www.devwares.com/docs/contrast/react/components/multiselect/)
- [Notification](https://www.devwares.com/docs/contrast/react/components/notification/)
- [Pane](https://www.devwares.com/docs/contrast/react/components/pane/)
- [Panel](https://www.devwares.com/docs/contrast/react/components/panels/)
- [Progress](https://www.devwares.com/docs/contrast/react/components/progress/)
- [Radio](https://www.devwares.com/docs/contrast/react/components/radio/)
- [Rating](https://www.devwares.com/docs/contrast/react/components/rating/)
- [Select](https://www.devwares.com/docs/contrast/react/components/select/)
- [Select 2](https://www.devwares.com/docs/contrast/react/components/select2/)
- [SmoothScroll](https://www.devwares.com/docs/contrast/react/components/smoothscroll/)
- [Slider](https://www.devwares.com/docs/contrast/react/components/slider/)
- [Spinner](https://www.devwares.com/docs/contrast/react/components/spinner/)
- [Stepper](https://www.devwares.com/docs/contrast/react/components/stepper/)
- [Switch](https://www.devwares.com/docs/contrast/react/components/switch/)
- [Navbar](https://www.devwares.com/docs/contrast/react/navigation/navbar/)
- [Pagination](https://www.devwares.com/docs/contrast/react/navigation/pagination/)
- [Sidebar](https://www.devwares.com/docs/contrast/react/navigation/sidebar/)
- [Tab](https://www.devwares.com/docs/contrast/react/navigation/tabs/)
- [Date Picker](https://www.devwares.com/docs/contrast/react/sections/datepicker/)
- [FileUploader](https://www.devwares.com/docs/contrast/react/sections/fileuploader/)
- [Time Picker](https://www.devwares.com/docs/contrast/react/sections/timepicker/)
- [Editable Table](https://www.devwares.com/docs/contrast/react/table/editabletable/)
- [Table](https://www.devwares.com/docs/contrast/react/table/table/)
- [Data Table](https://www.devwares.com/docs/contrast/react/table/datatables/)
- [Widgets]
(https://www.devwares.com/docs/contrast/react/widgets/)
- [Forms]
(https://www.devwares.com/docs/contrast/react/forms/)