Develop JavaScript to implement strings

Laboratory Objective:

  1. To be able to understand the concept of strings.
  2. To be able to use different string methods.

JavaScript Strings

  • JavaScript Strings are used for storing and manipulating text.
  • Strings in JavaScript can be enclosed within either “single quotes”, “double quotes” or “backticks”:
  • For example

var single_quoted  = 'Single quoted string';

var double_quoted = "double-quoted string";

var backticks = `backticks string`;

  • Backticks, allow us to embed any expression into the string, by wrapping it in ${…}:

function product(x, y)

{

 return x * y;

}

alert(`4 + 6 = ${product(4, 6)}.`);    // 4 * 6 = 24

  • Strings also can be created by using String’s fromCharCode() method.

String.fromCharCode(104,101,108,108,111)      // "hello"

  • String can also be created using String Object constructor along with new keyword

var objString = new String("I am a String object");

String length

  • The length property has the string length.
  • Note that str.length is a numeric property, not a function. There is no need to add parenthesis after it.

String Methods

  1. str.toLowerCase() : Converts a string to lowercase and returns a new string.
  2. str.toUpperCase() : Converts a string to UPPERCASE and returns a new string.
  3. str.indexOf(substr, [pos]) : Returns the index of (the position of) the first occurrence of a specified text in a string. Returns -1 if the text is not found.
  4. str.lastIndexOf(substr, [pos]) : Returns the index of the last occurrence of a specified text in a string.
  5. str.includes(substr, pos) : Determines whether substr is found in given string, returns either true or false.
  6. str.startsWith(searchbstr) : Determines whether a string begins with the characters of a specified string. Returns true or false depending on result.
  7. str.endsWith(searchstr) : Determines whether a string ends with the characters of a specified string. Returns true or false depending on result.
  8. str.slice(start [, end]) : Extracts a part of a string from start to end (not including end) and returns the extracted part in a new string. If a parameter is negative, the position is counted from the end of the string. If you omit the second parameter, the method will slice out the rest of the string
  9. str.substring(start [, end]) : Similar to slice(), extracts a part of a string between start and end. It cannot accept negative indexes and it allows start to be greater than end. Negative values mean 0
  10. str.substr(start [, length]) : Similar to slice(), extracts a part of a string the from start get length characters. If you omit the second parameter, substr() will slice out the rest of the string.
  11. str.trim() : Removes spaces from the beginning and end of the string.
  12. str.search(searchstr) : Searches a string for a specified string and returns the position of the match.
  13. str.replace(to, with) : Replaces a specified value with another value in a string.
  14. str.concat(string) : Joins two or more strings. This method can be used instead of the plus operator.
  15. str.charAt(index) : Returns the character at a specified index (position) in a string
  16. str.charCodeAt(index) : Returns the Unicode of the character at a specified index in a string. This method returns a UTF-16 code (an integer between 0 and 65535)
  17. str.split(seperator) : Splits a string into sub strings array. If the separator is “” (blank or not given), the returned array will be an array of single characters.

Sample Programs

1) Develop a program to change the case of string.

<html>

<head>

  <script>

     function toUpper() {

        var text = document.getElementById('panel').innerHTML

        document.getElementById('panel').innerHTML = text.toUpperCase()

     }

     function toLower() {

        var text = document.getElementById('panel').innerHTML

        document.getElementById('panel').innerHTML = text.toLowerCase()

     }

  </script>

</head>

<body>

  <p id="panel">Click on button to change case.</p>

  <input type="button" value="UPPERCASE" onclick="toUpper()" />

  <input type="button" value="lowercase" onclick="toLower()" />

</body>

</html>

2) Develop a JavaScript program to count the number of vowels in a given string.

<html>

<head>

   <title>Count vowels in a string</title>

</head>

<body>

<script>

var str = prompt('Enter the string', '')

var vowels = countVowels(str)

document.write("Given string: " + str)

document.write("<br>Number of Vowels: " + vowels)

function countVowels(s)

{

 var i=0, count=0

 var ch

 for(var i=0; i<s.length; i++)

 {

  ch = s.charAt(i)

  if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')

  {

   count++

  }

 }

 return count

}

</script>

</body>

</html>

3) Develop a program to construct the mailID as <name>.<surname>@domainname.com and display mail ID as message. (Ex. If user enters Rajni as name and Pathak as surname mailID will be constructed as rajni.pathak@domainname.com).

<html>

<head>

  <script>

     function constructMailId() {

        var fn = document.getElementById('fname').value

        var sn = document.getElementById('sname').value

        var email = fn.toLowerCase() + "." + sn.toLowerCase() + "@domainname.com"

        alert('Your mailID is: ' + email)

     }

  </script>

</head>

<body>

  <form name="myform">

     <p>

        First name <input type="text" id="fname" /><br />

        Surname <input type="text" id="sname" /><br />

        <input type="button" value="Submit" onclick="constructMailId()" />

     </p>

  </form>

</body>

</html>