CHAPTER - 18
String in Javascript
The String object is used for storing and manipulating text.
A string simply stores a series of characters like "John Doe".A string can be any text inside quotes. You can use single or double quotes:
Example:
var carname="My Name is Khan";
You can access each character in a string with its position
Example:
var character=carname[7];
String Length
<!DOCTYPE html>
<html><body>
<script>
var txt = "Hello World!";
document.write("<p>" + txt.length + "</p>");
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write("<p>" + txt.length + "</p>");
</script>
</body>
</html>
Finding a String in a String
The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string:
Examplevar str="Hello world, welcome to the universe welcome.";
var n=str.indexOf("welcome");
Match Content
Matching Content
The match() method can be used to search for a matching content in a string:<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
</script>
</body>
</html>
Replacing Content
The replace() method replaces a specified value with another value in a string.
Example:str="Please visit Microsoft!"
var n=str.replace("Microsoft","Acesoftech Academy");
CHANGE CASE
<!DOCTYPE html>
<html><body>
<script>
var txt="Hello World!";
document.write("<p>" + txt.toUpperCase() + "</p>");
document.write("<p>" + txt.toLowerCase() + "</p>");
document.write("<p>" + txt + "</p>");
</script>
<p>
The method returns a new string.
The original string is not changed.
</p>
</body>
</html>
Comments
Post a Comment