5️⃣

6.5 String Methods

6.5 String Methods

String Length

💡

Not a method, but in the same ballpark.

The length property returns the length of a string:

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

let str = "Please locate where 'locate' occurs!";
let pos = str.indexOf("locate");

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

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

Both indexOf(), and lastIndexOf() return -1 if the text is not found.

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

Searching for a String in a String

The search method searches a string for a specified value and returns the position of the match:

let str = "Please locate where 'locate' occurs!";
let pos = str.search("locate");

Practice

You can add practice problems here if you want. Follow the format below.

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.