String
Split
String split into serval arrays
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
//fox
Sub String
const str = 'Mozilla';
console.log(str.substring(1, 3));
// expected output: "oz"
console.log(str.substring(2));
// expected output: "zilla"
Searching
const string = "Hello World!";
// finding character at index 1
let index1 = string.charAt(1);
// e
let code1 = string.charCodeAt(1);
// 101
const message = "JavaScript is not Java";
// returns index of 'v' in first occurrence of 'va'
const index = message.indexOf("va");
console.log('index: ' + index);
// index: 2
// search is similar with indexOf, but also accept regex
let sentence= "I love JavaScript.";
let regExp = /Java/g;
let indexReg = sentence.search(regExp);
console.log(indexReg);
// Output: 7
Check true/false
const str1 = 'Saturday night plans';
console.log(str1.startsWith('Sat'));
// expected output: true
console.log(str1.startsWith('ur', 3));
// expected output: true
const message = "JavaScript is fun";
// check if message includes the string "Java"
let result = message.includes("Java");
console.log(result);
// Output: true
Concat
let emptyString = "";
// joint arguments string
let joinedString = emptyString.concat("JavaScript", " is", " fun.");
console.log(joinedString);
// Output: JavaScript is fun.
Matching
const message = "programming is a fun programming language.";
// regular expression that checks if message contains 'programming'
const exp = /programming/g;
const exp2 = /hi/g;
// check if exp is present in message
let result = message.match(exp);
let result2 = message.match(exp2);
console.log(result,result2);
// [programming, programming], null
// Match all includes result and captured group
const regexp = /t(e)st(\d?)/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array);
// [["test1", "e", "1"], ["test2", "e", "2"]]
const regexp = /t(e)st(\d?)/g;
const str = 'test1test2';
const array = [...str.match(regexp)];
console.log(array);
// ["test1", "test2"]
Pad
// string definition
let string1 = "CODE";
// padding "*" to the start of given string
// until the length of final padded string reaches 10
let paddedString = string1.padStart(10, "*");
console.log(paddedString);
// Output: ******CODE
Repeat
const holiday = "Happy holiday!";
// repeating the given string 3 times
const result = holiday.repeat(3);
console.log(result);
// Output:
// Happy holiday!Happy holiday!Happy holiday!
Replace
const message = "ball bat";
let result = message.replace('b', 'c');
let result1 = message.replaceAll('b', 'c');
console.log(result, result1);
// Output: call bat, call cat
Slice
const message = "JavaScript is fun";
// slice the substring from index 0 to 10
let result = message.slice(0, 10);
console.log(result);
// Output: JavaScript
Last updated
Was this helpful?