Working with Strings in JavaScript

String plays an important role in every programming languages. JavaScript is no exception. Also every character in JavaScript is represented by some number. That numerical unicode is known as charcode of that character. Example, 'A' is represented by 65.

Here are few functions that can be useful to help you out with your day to day coding work.

String Concatenation

String concatenation refers to combining one string to another. Simplest way to join strings is using '+' (plus) operator. But there is also a method concat() which can be used to unite strings together.

Syntax

//using concat method
string1.concat(string2, string3, ...);

//using + operator
string1 + string2 + string3

Example

<script>

var str = "Syntax";
str = str.concat("Page"); //SyntaxPage
document.write(str);
document.write("<br />");

str = "JavaScript";
str = str.concat(" is", " fun", "<br />");
document.write(str); //JavaScript is fun

str = "JavaScript " + "is " + "awesome" + "<br />";
document.write(str); //JavaScript is awesome

</script>

Splitting Strings

Various methods are available in JavaScript to get whole or some part of strings. Few commonly used methods are as follows:

substring() method

substring method is used to get arbitrary string values between the index positions passed to it as parameters.

Syntax

string.substring(start,[end])

First parameter specifies from where to copy the string. Second optional parameter specifies till where to copy. Also, character specified by second parameter is not included. If second parameter is not given then whole string after start position will be copied.

Example

<script>

var str = 'SyntaxPage';
var sub = str.substring(6); //Page
document.write(sub);
document.write("<br />)

str = 'JavaScript';
sub = str.substring(4,7); //Src
document.write(sub);
//element at 4th position is excluded

</script>

substr() method

substr method is somewhat similar to substring() method with just one difference. The second parameter in the substr() method specifies the length of the string to be copied, not the end position.

Syntax

string.substr(start,length)

Example

<script>

var str = 'SyntaxPage';
var sub = str.substr(6); //Page
document.write(sub);
document.write("<br />")

str = 'JavaScript';
sub = str.substr(4,3); //Scr
document.write(sub);

</script>

slice() method

slice method is used to get characters from a string between specified indexes passed to it as parameters.

Syntax

string.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be from start index till the end of the string.

Example

<script>

var str = "12345";
var sub = str.slice(1, 4); //234
document.write(sub);
document.write("<br />");

sub = str.slice(1); //2345
document.write(sub);

</script>

split() method

split() method breaks a string into an array of string. It splits the string from the separator string boundaries that is passed to it as parameter.

Syntax

string.split(separator,[size])

If no separator string is given then it will break the string into an array having just one element which is string itself.

If optional size parameter is given then array formed will be of given size parameter ignoring the rest of the characters.

Example

<script>

var str = "JavaScript is fun";
var sub = str.split(" ");
document.write(sub); //JavaScript,is,fun
document.write("<br />");

sub = str.split(" ", 1);
document.write(sub); //JavaScript
document.write("<br />");

sub = str.split();
document.write(sub[0]); //JavaScript is fun

</script>

Changing Case

toLowerCase() method

toLowerCase() method is used to change the case of the string to lower case.

Syntax

string.toLowerCase()

Example

<script>

var str = "JavaScript is Awesome";
var lcase = str.toLowerCase();
document.write(lcase);

</script>

toUpperCase() method

toUpperCase() method is used to change the case of the string to upper case.

Syntax

string.toUpperCase()

Example

<script>

var str = "JavaScript is Awesome";
var ucase = str.toUpperCase();
document.write(ucase);

</script>

Finding Characters

indexOf() method

indexOf() method is used to search for a given substring in the parent string and returns substring position.

Syntax

string.indexOf(needle,[fromIndex])

Optional second parameter decides from where to begin searching the string. It starts searching from the beginning if optional second parameter is not given. In case needle(substring) is not found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";
var pos = str.indexOf("Script"); //4
document.write(pos);
document.write("<br />");

var pos = str.indexOf("Script",5); //25
document.write(pos);

</script>

lastIndexOf() method

lastIndexOf() method is used to search for a given substring beginning the search from the end. It returns needle's position. In case needle(substring) is not found then it returns -1.

Syntax

string.lastIndexOf(needle,[fromIndex])

It starts searching from the end if optional second parameter is not given. In case needle(substring) is not found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";
var pos = str.lastIndexOf("Script"); //25
document.write(pos);

var pos = str.lastIndexOf("Script",24); //4
document.write(pos);

</script>

search() method

search() returns the index position of the needle if found else it returns -1. It looks somewhat similar to indexOf() method but seach() method works with regular expressions. Regular expressions will be discussed later.

Syntax

string.search(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";
var pos = str.search("Script"); //4
document.write(pos);

</script>

match() method

match() returns the substring(needle) if found in the main string else it returns null. match() method also works with regular expressions. Performance wise indexOf() method is faster than match() and search().

Syntax

string.match(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";
var pos = str.match("Script"); //Script
document.write(pos);

</script>

charAt() method

charAt() returns the character at a particular index which is passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";
var c = str.charAt(4); //S
document.write(c);

</script>

charCodeAt() method

charCodeAt() returns the unicode numeric value of a character at a particular index which is passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";
var u = str.charCodeAt(4); //83
document.write(u);

</script>

Replacing word in a string

replace() method

replace() method is used to find and replace some or all occurrence of a string/character with some new specified string/character within a string. To replace more than one value within a string pass regular expression as first argument.

Syntax

string.replace(regular_expression/string, 'new_string')

Example

<script>

var str = "JavaScript is Awesome";
var newStr = str.replace("Awesome", "Amazing");
document.write(newStr);

</script>

Summary of String Methods in JavaScript

Method Description
str.concat(str1, str2,...) combines one or more string
str.substring(start,[end]) returns substring from start to end unless end index position is specified
str.substr(start,len) returns substring from start to end unless number of characters(length) is specified
str.slice(start, [end]) returns substring between specified indexes
str.split(sep,[size]) breaks a string into an array from the separator string boundaries
str.toLowerCase() returns lowercase string
str.toUpperCase() returns uppercase string
str.indexOf(needle,[fromIndex]) returns character present at specified index beginning the search from start. Second parameter decides from where to begin search
str.lastIndexOf(needle,[fromIndex]) returns character present at specified index beginning the search from end. Second parameter decides from where to begin search
str.search(regexp) returns the index position of the substring if found else it returns -1
str.match(regexp) returns the substring if found else it returns null.
str.charAt(index) returns the character at a particular index which is passed to it as an argument
str.charCodeAt(index) returns the unicode numeric value of a character at a particular index which is passed to it as an argument
str.replace(regular_expression/string, "new_string") returns string after replacing some or all occurrence of old string with new string within a given string.
<< Working with Numbers Date and Time >>