JavaScript Strings - Exercise 5
You can find the length of a string in JavaScript using
the length property.
var str = 'hello';
var length = str.length; // length will be 5
You can check if a string starts or ends with a specific
substring in JavaScript using the
startsWith() and
endsWith() methods, respectively.
var str = 'hello world';
var startsWithHello = str.startsWith('hello'); // startsWithHello will be true
var endsWithWorld = str.endsWith('world'); // endsWithWorld will be true
You can remove whitespace from the beginning and end of
a string in JavaScript using the
trim() method.
var str = ' hello world ';
var trimmedStr = str.trim(); // trimmedStr will be 'hello world'
You can replace a substring within a string in
JavaScript using the replace() method.
var str = 'hello world';
var newStr = str.replace('world', 'universe'); // newStr will be 'hello universe'
You can extract a substring from a string in JavaScript
using the substring() method.
var str = 'hello world';
var substring = str.substring(6, 11); // substring will be 'world'
You can check if a string is empty in JavaScript by comparing its length to zero.
var str = '';
var isEmpty = str.length === 0; // isEmpty will be true
You can check if a string contains only alphabetic characters in JavaScript using regular expressions.
var str = 'Hello';
var isAlpha = /^[a-zA-Z]+$/.test(str); // isAlpha will be true
You can convert a string to title case by lowercasing the text first and then capitalizing the first letter of each word.
function toTitleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, function (char) {
return char.toUpperCase();
});
}
const titleCaseStr = toTitleCase('hello world'); // 'Hello World'
You can convert a string to camel case by keeping the first word lowercase and capitalizing later words while removing separators.
function toCamelCase(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function (match, char) {
return char.toUpperCase();
});
}
const camelCaseStr = toCamelCase('hello world'); // 'helloWorld'
You can check whether a string is a palindrome by normalizing it and comparing it with its reversed version.
function isPalindrome(str) {
const normalized = str.toLowerCase().replace(/\s/g, '');
const reversed = normalized.split('').reverse().join('');
return normalized === reversed;
}
const isPal = isPalindrome('radar'); // true