At some point, you may need to transform/manipulate strings to output them in the way that you want/need. You can write custom methods, but I think there's something here for you. I present to you several javascript methods for text formatting!
concat()
Combines the text of two strings and returns a new string.
let string1 = 'Hello' let string2 = 'world!' let string3 = string1.concat(' ', string2) console.log(string3) // expected output: 'Hello world!'
split()
Splits a String object into an array of strings by separating the string into substrings.
let string1 = 'I!am!saying!hello!to!the!world' string1.split('!') // expected output:['I','am','saying','hello','to','the','world']
toLowerCase(),toUpperCase()
Return the string in all lowercase or all uppercase, respectively.
let string = "Hello World!" let upperString = string.toUpperCase() let lowerString = string.toLowerCase() console.log(upperString) // expected output: HELLO WORLD! console.log(lowerString) // expected output: hello world!
slice()
Extracts a section of a string and returns a new string.
let string = "Hello World!" console.log(string.slice(0)) //expected output: Hello World! console.log(string.slice(5)) //expected output: World! console.log(string.slice(-1)) //expected output: !
match(), matchAll(), replace(), replaceAll(), search()
Work with regular expressions.
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found); // expected output: Array ["T", "I"] const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; console.log(p.replace(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replace('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
trim()
Trims whitespace from the beginning and end of the string.
const greeting = ' Hello world! '; console.log(greeting); // expected output: " Hello world! "; console.log(greeting.trim()); // expected output: "Hello world!";
Top comments (0)