Exercise

You can pad a string with leading zeros in JavaScript using the padStart() method.

javascript

var str = '5';
var paddedStr = str.padStart(2, '0'); // paddedStr will be '05'

You can find the index of a substring within a string in JavaScript using the indexOf() method.

javascript

var str = 'hello world';
var index = str.indexOf('world'); // index will be 6

You can convert a string to lowercase or uppercase in JavaScript using the toLowerCase() and toUpperCase() methods, respectively.

javascript

var str = 'Hello World';
var lowerCaseStr = str.toLowerCase(); // lowerCaseStr will be 'hello world'
var upperCaseStr = str.toUpperCase(); // upperCaseStr will be 'HELLO WORLD'

You can convert a string to a number in JavaScript using the parseInt() or parseFloat() functions.

javascript

var str = '123';
var num = parseInt(str); // num will be 123

You can truncate a string in JavaScript using the slice() method.

javascript

var str = 'hello world';
var truncatedStr = str.slice(0, 5); // truncatedStr will be 'hello'

You can repeat a string in JavaScript using the repeat() method.

javascript

var str = 'hello';
var repeatedStr = str.repeat(3); // repeatedStr will be 'hellohellohello'

You can split a string into an array of substrings in JavaScript using the split() method.

javascript

var str = 'hello world';
var substrings = str.split(' '); // substrings will be ['hello', 'world']

You can join elements of an array into a string in JavaScript using the join() method.

javascript

var arr = ['hello', 'world'];
var str = arr.join(' '); // str will be 'hello world'

You can reverse a string in JavaScript using various methods, such as looping, split() and reverse(), or the spread operator.

javascript

// Using loop
function reverseString(str) {
    var reversed = '';
    for (var i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
}

// Using split() and reverse()
function reverseString(str) {
    return str.split('').reverse().join('');
}

// Using spread operator
function reverseString(str) {
    return [...str].reverse().join('');
}

var reversed = reverseString('hello'); // reversed will be 'olleh'

You can check if a string contains another substring in JavaScript using the includes() method or regular expressions.

javascript

var str = 'hello world';
var containsSubstring = str.includes('world'); // containsSubstring will be true