Javascript String
Javascript String
The charAt() method returns the character at a specified index (position) in a string:
Example
let text = "HELLO WORLD";
let char = text.charAt(6);
The charCodeAt() method returns the code of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
JavaScript String at()
The at() method returns the character at a specified index (position) in a string.
The at() method is supported in all modern browsers since March 2022:
JavaScript String Search
JavaScript String indexOf()
The indexOf() method returns the index (position) of the first occurrence of a string in a string, or it
returns -1 if the string is not found:
Example
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
JavaScript String lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
Example
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
The search() method searches a string for a string (or a regular expression) and returns the position of
the match:
Examples
let text = "Please locate where 'locate' occurs!";
text.search("locate");
JavaScript String match()
The match() method returns an array containing the results of matching a string against a string (or a
regular expression).
Examples
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
The slice() Method
Hello
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.slice(3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
<html>
<body>
<h1>JavaScript Strings</h1>
<script>
</script>
</body>
</html>
replace() searches a string for a value, and returns a new string with the specified value(s) replaced:
Visit W3Schools!
JavaScript String replaceAll()
<html>
<body>
<h1>JavaScript Strings</h1>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The replaceAll() Method
I love dogs. Dogs are very easy to love. Dogs are very popular.
String indexOf()
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>
<p>Find "welcome":</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
The indexOf() Method
Find "welcome":
13