PK-WT-Unit 04 - JavaSCript String Object
PK-WT-Unit 04 - JavaSCript String Object
String Object
String Object
• Strings are objects within the JavaScript language. They are not stored as character
arrays, so built-in functions must be used to manipulate their values.
str[0]
• Property access might be a little unpredictable. It makes strings look like arrays (but
they are not).
JavaScript String indexOf()
• The indexOf() method returns the index of (the position of) the first occurrence of a specified
text in a string.
• Coding:
<script>
var str = “Javascript is easy to learn";
document.getElementById("demo").innerHTML = str.indexOf(“easy");
</script>
• Output:
14
JavaScript String lastIndexOf()
• Output:
The lastIndexOf() method returns the index of the last occurrence of a specified text in a
Coding:
string.
23
<script>
var str = “Javascript is easy to learn";
document.getElementById("demo").innerHTML = str.lastIndexOf("e");
</script>
• Both indexOf(), and lastIndexOf() return -1 if the text is not found.
• 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.
JavaScript String search()
The search() method searches a string for a specified value and returns the position of the
match
• 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).
Output:
Coding:
14
<script>
var str = “JavaScript is easy to learn";
document.getElementById("demo").innerHTML = str.search(“e");
</script>
JavaScript String match()
• The match() method searches a string for a match against a regular expression,
and returns the matches, as an Array object.
• Coding:
<script>
let text = "The rain in SPAIN stays mainly in the plain";
document.getElementById("demo").innerHTML = text.match(/ain/g);
</script>
Output:
ain,ain,ain.
JavaScript String includes()
The includes() method returns true if a string contains a specified value.
• Syntax
string.includes(searchvalue, start).
Coding:
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world", 12);
</script>
Output:
false
JavaScript String startsWith()
The startsWith() method returns true if a string begins with a specified value,
Output:
otherwise
True false.
Coding:
<script>
let text = "Hello world";
document.getElementById("demo").innerHTML = text.startsWith("o",4);
YOU
H ANK
T