Mastery
JavaScript » Strings

Length

Find the length of a string:

var txt = "Taggerung";
var sln = txt.length;

Finding a String in a String

The indexOf() method returns the index of the first occurrence of a specified text in a string:

<p id="p1">Please locate where 'locate' occurs!</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>     <!-- This will show "7" -->

<script>
function myFunction() {
    var str = document.getElementById("p1").innerHTML;
    var pos = str.indexOf("locate");
    document.getElementById("demo").innerHTML = pos;
}
</script>

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

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

Slicing

This extracts a part of a string and returns the extracted part in a new string:

<p id="demo"></p>     <!-- This will show "Banana" -->

<script>
var str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(7,13);
</script>

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

var res = str.slice(7);   // Put in above code, this will show just "Banana, Kiwi"

The difference in substr() is that the second parameter specifies the length of the extracted part. If the first parameter is negative, the position counts from the end of the string. If you omit the second parameter, substr() will slice out the rest of the string.

var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);   // Put in above code, this will show just "Banana"

Convert to Upper and Lower Case

Convert to upper case:

<button onclick="myFunction()">Try it</button>

<p id="demo">Expelliarmus!</p>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML = text.toUpperCase();
}
</script>

Convert to lower case:

var text1 = "Rictusempra!";       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower

Merge Strings

concat() joins two or more strings. It can be used instead the plus operator.

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");   // Does the same thing as previous line

Convert to an Array

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

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