- JavaScript Introduction
- JavaScript Where To
- JavaScript Output
- JavaScript Statements
- JavaScript Syntax
- JavaScript Comments
- JavaScript Variables
- JavaScript Let
- JavaScript Const
- JavaScript Operators
- JavaScript Assignment
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Const
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Random
- JavaScript Booleans
- JavaScript Comparison And Logical Operators
- JavaScript If Else And Else If
- JavaScript Switch Statement
- JavaScript For Loop
- JavaScript Break And Continue
- JavaScript Type Conversion
- JavaScript Bitwise Operations
- JavaScript Regular Expressions
- JavaScript Errors
- JavaScript Scope
- JavaScript Hoisting
- JavaScript Use Strict
- The JavaScript This Keyword
- JavaScript Arrow Function
- JavaScript Classes
- JavaScript JSON
- JavaScript Debugging
- JavaScript Style Guide
- JavaScript Common Mistakes
- JavaScript Performance
- JavaScript Reserved Words
- JavaScript Versions
- JavaScript History
- JavaScript Forms
- JavaScript Validation API
- JavaScript Objects
- JavaScript Object Properties
- JavaScript Function Definitions
- JavaScript Function Parameters
- JavaScript Function Invocation
- JavaScript Closures
- JavaScript Classes
- Java Script Async
- JavaScript HTML DOM
- The Browser Object Model
- JS Ajax
- JavaScript JSON
- JavaScript Web APIs
- JS Vs JQuery
JavaScript String Methods
String Methods And Properties
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String Length
The length
property returns the length of a string:
Example
var sln = txt.length;
Finding a String in a String
The indexOf()
method returns the index of (the position of) the first
occurrence of a specified text in a string:
Example
var pos = str.indexOf("locate");
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
The lastIndexOf()
method returns the index of the last occurrence of a specified text in a string:
Example
var pos = str.lastIndexOf("locate");
Both indexOf()
, and lastIndexOf()
return -1 if the text is not found.
Example
var pos = str.lastIndexOf("John");
Both methods accept a second parameter as the starting position for the search:
Example
var pos = str.indexOf("locate", 15);
The lastIndexOf()
methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15
, the search starts at position 15, and searches to the beginning of the string.
Example
var pos = str.lastIndexOf("locate", 15);
Practice Excercise Practice now
Searching For A String In A String
The search()
method searches a string for a specified value and returns the position of the match:
Example
var pos = str.search("locate");
Did You Notice?
The two methods, indexOf()
and search()
, are equal?
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
- The
search()
method cannot take a second start position argument. - The
indexOf()
method cannot take powerful search values (regular expressions).
Practice Excercise Practice now
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method
slice()
extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
var res = str.slice(7, 13);
The result of res will be:
Banana
Remember: JavaScript counts positions from zero. First position is 0.
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:
Example
var res = str.slice(-12, -6);
The result of res will be:
Banana
If you omit the second parameter, the method will slice out the rest of the string:
Example
or, counting from the end:
Example
The substring() Method
substring()
is similar to slice()
.
The difference is that substring()
cannot accept negative indexes.
Example
var res = str.substring(7, 13);
The result of res will be:
Banana
If you omit the second parameter,
substring()
will slice out the rest of the string.The substr() Method
substr()
is similar to slice()
.
The difference is that the second parameter specifies the length of the extracted part.
Example
var res = str.substr(7, 6);
The result of res will be:
Banana
If you omit the second parameter, substr()
will slice out the rest of the string.
Example
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.
Example
var res = str.substr(-4);
The result of res will be:
Kiwi
Practice Excercise Practice now
Replacing String Content
The replace()
method replaces a specified value with another value in a string:
Example
var n = str.replace("Microsoft", "Mytat");
The replace()
method does not change the string it is called on. It returns a new string.
By default, the replace()
method replaces only the first match:
Example
var n = str.replace("Microsoft", "Mytat");
By default, the replace()
method is case sensitive. Writing MICROSOFT (with upper-case) will not work:
Example
var n = str.replace("MICROSOFT", "Mytat");
To replace case insensitive, use a regular expression with an /i
flag (insensitive):
Example
var n = str.replace(/MICROSOFT/i, "Mytat");
Note that regular expressions are written without quotes.
To replace all matches, use a regular expression with a /g
flag (global match):
Example
var n = str.replace(/Microsoft/g, "Mytat");
Practice Excercise Practice now
Converting To Upper And Lower Case
A string is converted to upper case with toUpperCase()
:
Example
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase()
:
Example
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Practice Excercise Practice now
The Concat() Method
concat()
joins two or more strings:
Example
var text2 = "World";
var text3 = text1.concat(" ", text2);
The concat()
method can be used instead of the plus operator. These two lines do the same:
Example
var text = "Hello".concat(" ", "World!");
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
Practice Excercise Practice now
String.trim()
The trim()
method removes whitespace from both sides of a string:
Example
alert(str.trim());
The trim()
method is not supported in Internet Explorer 8 or lower.
If you need to support IE 8, you can use replace()
with a regular expression instead:
Example
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
:
Example
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
var str = " Hello World! ";
alert(str.trim());
Practice Excercise Practice now
JavaScript String Padding
ECMAScript 2017 added two String methods: padStart
and padEnd
to support padding at the beginning and at the end of a string.
Example
str = str.padStart(4,0);
// result is 0005
Example
str = str.padEnd(4,0);
// result is 5000
String Padding is not supported in Internet Explorer.
Firefox and Safari were the first browsers with support for JavaScript string padding:
Chrome 57 | Edge 15 | Firefox 48 | Safari 10 | Opera 44 |
Mar 2017 | Apr 2017 | Aug 2016 | Sep 2016 | Mar 2017 |
Practice Excercise Practice now
Converting A String To An Array
A string can be converted to an array with the split()
method:
Example
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.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
txt.split(""); // Split in characters
Practice Excercise Practice now
How To Recognize An Array
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof
returns "object
":
typeof fruits; // returns object
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray()
:
The problem with this solution is that ECMAScript 5 is not supported in older browsers.
Solution 2:
To solve this problem you can create your own isArray()
function:
return x.constructor.toString().indexOf("Array") > -1;
}
The function above always returns true if the argument is an array.
Or more precisely: it returns true if the object prototype contains the word "Array".
Solution 3:
The instanceof
operator returns true if an object is created by a given constructor:
fruits instanceof Array; // returns true
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP