Exercise

You can find the length of a string in JavaScript using the length property.

javascript

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.

javascript

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.

javascript

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.

javascript

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.

javascript

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.

javascript

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.

javascript

var str = 'Hello';
var isAlpha = /^[a-zA-Z]+$/.test(str); // isAlpha will be true

You can convert a string to title case in JavaScript by capitalizing the first letter of each word.

javascript

function toTitleCase(str) {
    return str.toLowerCase().replace(/(^|\s)\S/g, function (char) {
        return char.toUpperCase();
    });
}

var titleCaseStr = toTitleCase('hello world'); // titleCaseStr will be 'Hello World'

You can convert a string to camel case in JavaScript by removing spaces and capitalizing the first letter of each word except the first one.

javascript

function toCamelCase(str) {
    return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function (match, char) {
        return char.toUpperCase();
    });
}

var camelCaseStr = toCamelCase('hello world'); // camelCaseStr will be 'helloWorld'

You can check if a string is a palindrome in JavaScript by comparing it with its reverse.

javascript

function isPalindrome(str) {
    var reversed = str.split('').reverse().join('');
    return str === reversed;
}

var isPal = isPalindrome('radar'); // isPal will be true