JS String Methods & Properties

HTML
CSS
C#
SQL

String Methods & Properties

JavaScript strings, whether primitive or represented as String objects, come with default properties and methods. These tools allow you to perform various operations on strings. Let’s dive into some key properties and methods:

Getting the Length of a String

The `length` property returns the number of characters in a string:

String Methods for Different Purposes

JavaScript provides an array of string methods catering to various tasks. Here are some important ones:

1. Searching Methods:

– `indexOf()`: Returns the position of the first occurrence of a specified text within a string.

– `lastIndexOf()`: Returns the position of the last occurrence of a specified text within a string.

2. Extracting Methods:

– slice(start, end): Extracts a part of a string and returns a new string.

– substring(start, end): Similar to `slice()`, but cannot accept negative indexes.

3. Modifying Methods:

– replace(searchValue, replaceValue): Searches a string for a specified value and replaces it with another value.

You can update the content of HTML elements by accessing them with JavaScript and modifying their innerHTML or textContent properties.

– toUpperCase() and toLowerCase(): Convert a string to uppercase or lowercase.

Take a look at the full list of string methods below

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a JavaScript Program to Trim a String.

The task is to write a JavaScript program that takes a sample string, trims it using the trim() method, and then outputs both the original and trimmed strings to the console for verification. The trim() method is useful for removing unnecessary spaces, which can be particularly handy when dealing with user input or manipulating strings in various contexts.

Sample string:
inputString = ” Hello, World! “;

Here’s a simple JavaScript program that trims a string using the trim() method:

// Sample string with leading and trailing spaces
let inputString = ” Hello, World! “;

// Using trim() to remove leading and trailing spaces
let trimmedString = inputString.trim();

// Output the original and trimmed strings
console.log(“Original String: ‘” + inputString + “‘”);
console.log(“Trimmed String: ‘” + trimmedString + “‘”);

Output

2. Write a js program to take a lowercase string as input from a user and convert that string into UpperCase.

The task is to write a JavaScript program that takes a lowercase string as input from a user and converts that string into uppercase.
1. User Input: Use the prompt() function to get input from the user. Prompt the user to enter a lowercase string.
2. String Conversion: Take the input string and use a method like toUpperCase() to convert the string to uppercase. This ensures that all characters in the string are in uppercase.
3. Output Result: Display the converted uppercase string, either by logging it to the console or using an alert, depending on the desired method of output.

Here’s a JavaScript program that prompts the user to input a string, and then converts that string into uppercase:

// Prompt user to input a lowercase string
let lowercaseInput = prompt(“Enter a lowercase string:”);

// Convert the string to uppercase
let uppercaseString = lowercaseInput.toUpperCase();

// Output the result
console.log(“Original String: ” + lowercaseInput);
console.log(“Uppercase String:”, uppercaseString);

Output

3. Write a JavaScript Program to Compare Two Strings Using toUpperCase().

The task is to write a JavaScript program that takes two sample strings, converts them to uppercase using the toUpperCase() method, and subsequently compares the uppercase versions of the strings for case-insensitive equality. The result is then logged to the console.
Sample Strings:
string1 = “Hello”;
string2 = “hello”;

Here’s a simple JavaScript program that compares two strings using the toUpperCase() method:

// Sample strings for comparison
let string1 = “Hello”;
let string2 = “hello”;

// Convert strings to uppercase and compare
let uppercaseString1 = string1.toUpperCase();
let uppercaseString2 = string2.toUpperCase();

// Compare the uppercase strings
if (uppercaseString1 === uppercaseString2) {
console.log(“The strings are equal (case-insensitive).”);
} else {
console.log(“The strings are not equal (case-insensitive).”);
}

Output

4. Write a js program to print “IQRA TECHNOLOGY” on the document and print the length of the string and the last index of “O” print both in alert and on the document as well.

The task is to write a JavaScript program that does the following:
1. Print the string “IQRA TECHNOLOGY” on the document.
2. Calculate and print the length of the string.
3. Determines and prints the last index of the character “O”.
4. Shows both the length and the last index of “O” in an alert, as well as on the document.

Here’s an example program:

// Step 1: Print the string on the document
document.write(“IQRA TECHNOLOGY<br>”);

// Step 2: Calculate and print the length of the string
let originalString = “IQRA TECHNOLOGY”;
let stringLength = originalString.length;
document.write(“Length of the string: ” + stringLength + “<br>”);

// Step 3: Determine and print the last index of the character “O”
let lastIndexO = originalString.lastIndexOf(“O”);
document.write(“Last index of ‘O’: ” + lastIndexO + “<br>”);

// Step 4: Show length and last index of “O” in an alert
alert(“Length of the string: ” + stringLength + “\nLast index of ‘O’: ” + lastIndexO);

Output

This program first prints “IQRA TECHNOLOGY” on the document. Then, it calculates and prints the length of the string and determines the last index of the character “O.” Finally, it displays both the length and last index of “O” in an alert and prints them on the document as well.

5. Write a JavaScript program that takes the string “we are learning HTML & CSS” and replaces “HTML & CSS” with “JavaScript.” After the replacement, display the new string on the document with a length of string using a string method.

The task is to write a JavaScript program that does the following:
1. Takes the string “we are learning HTML & CSS.”
2. Replaces the substring “HTML & CSS” with “JavaScript” in the given string.
3. Displays the new string on the document.
4. Calculates and displays the length of the new string using a string method.

Here’s an example program:

// Step 1: Initial string
let originalString = “we are learning HTML & CSS.”;

// Step 2: Replace “HTML & CSS” with “JavaScript”
let newString = originalString.replace(“HTML & CSS”, “JavaScript”);

// Step 3: Display the new string on the document
document.write(“Original String: ” + originalString + “<br>”);
document.write(“New String: ” + newString + “<br>”);

// Step 4: Calculate and display the length of the new string using a string method
let newStringLength = newString.length;
document.write(“Length of the New String: ” + newStringLength + “<br>”);

Output

6. Write a JavaScript program that attempts to get the text content of an HTML element with the tag name “p.” convert the text content of the first “p” element to uppercase and display it using console.log().

The task is to create a JavaScript program that interacts with an HTML document. Specifically, the program should:
1. Find the first HTML <p> (paragraph) element.
2. Retrieve the text content of that <p> element.
3. Convert the text content to uppercase.
4. Display the uppercase text using console.log().
6. Paragraph content:
<p>This is a sample paragraph.</p>
<p>Another paragraph here.</p>

Here’s an example program:

<body>
<p>This is a sample paragraph.</p>
<p>Another paragraph here.</p>

<script>
// Get the first <p> element
var firstParagraph = document.querySelector(‘p’);

// Check if a <p> element was found
if (firstParagraph) {
// Retrieve the text content of the first <p> element
var textContent = firstParagraph.textContent;

// Convert the text content to uppercase
var uppercaseText = textContent.toUpperCase();

// Display the uppercase text using console.log()
console.log(“Original Text: ” + textContent);
console.log(“Uppercase Text: ” + uppercaseText);
} else {
console.log(“No <p> element found on the page.”);
}
</script>
</body>

Output

7. Write a JavaScript program that takes input from the user as “IQRA TECHNOLOGY.” Using a string method, extract the string “IQRA” from the entered string and display it along with its length. display the extracted string and its length?

The task is to create a JavaScript program that interacts with user input and performs the following tasks:
1. User Input: Prompt the user to input a string, and in this case, the string is “IQRA TECHNOLOGY.”

2. String Extraction: Use a string method to extract a specific substring from the entered string. In this case, you need to extract the substring “IQRA.”
3. Display Results: Display the extracted substring (“IQRA”) and its length using console.log().

Here’s an example program:

// Prompt the user to enter a string
var userInput = prompt(“Enter a string:”);

// Use a string method to extract the substring “IQRA”
var extractedString = userInput.slice(0, 4); // Using slice() method

// Display the extracted string and its length
console.log(“Original String: ” + userInput);
console.log(“Extracted String: ” + extractedString);
console.log(“Length of Extracted String: ” + extractedString.length);

Output