Unit3_JS_stringmethods.pptx-1
Unit3_JS_stringmethods.pptx-1
Dr Anupama Jha
JavaScript Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
You can use single or double quotes.
String Length
To find the length of a string, use the built-in length property.
Dr Anupama Jha
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<script>
// x is a string
let x = "John";
// y is an object
let y = new String("John");
document.write(typeof x + "<br>" +
typeof y);
</script></body></html>
Dr Anupama Jha
Javascript objects cannot be compared.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<script>
// x and y are objects
if (x==y)
alert("equal");
else
alert("not equal");
Dr Anupama Jha
JavaScript String Methods
Dr Anupama Jha
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<script>
let str = "vivekanandainstitute";
document.write(str.slice(7,13)); //str starts from 0 index,
slice will not include the end index value
document.write("<br>"+str.slice(-1));//last char
</script></body></html>
Dr Anupama Jha
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string and returns the
extracted parts in a new string:</p>
<script>
let str = "vivekanandainstitute";
document.write("<br>"+"Slice operation"+"<br>");
document.write(str.slice(7,13)); //str starts from 7 index till 12, slice will
not include the end index value
document.write("<br>"+str.slice(-14,-6));
document.write("<br>"+"Substring operation"+"<br>");
document.write(str.substr(7,5)); //str starts from 7 index, till 4 more
characters, total 5 characters
document.write("<br>"+str.substr(-7)); // -7 to end
</script></body></html>
Dr Anupama Jha
Dr Anupama Jha
The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match
By default, the replace() method replaces only the first match.
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not
work.
Dr Anupama Jha
Dr Anupama Jha