Creating New Strings

Most string methods in JavaScript create and return new strings, instead of altering the original. But the following methods are used modified the characters of the original strings to create a whole new string.

concat()

The concat()open in new window method is used to concatenate strings together. This is alternative to using the plus sign (+). The method accepts multiple string arguments.

const greeting = 'Hello'
const subject = 'World'

// combine greeting and subject with a comma and space between
console.log(greeting.concat(', ', subject)) // 'Hello, World'

repeat()

The repeat()open in new window method is creates and returns a new string by combining the specified number of copies of the string tother.

const chant = 'I think I can. '

// repeat chant three times.
console.log(chant.repeat(3)) // 'I think I can. I think I can. I think I can.'

replace()

This YouTube video was created by Steve Griffith.

The replace()open in new window method returns a new string with some or all matches of a pattern replaced by a replacement.

const chant = 'I think I can.'

console.log(chant.replace('think', 'know')) // 'I know I can.'

The pattern can also be a regular expression, which will allow multiple occurrences of the pattern to be replaced.

const title = 'The Little Engine that Could'

// create a slug from the title
console.log(title.replace(/\s/g, '-').toLowerCase()) // 'the-little-engine-that-could'

trim()

This YouTube video was created by Steve Griffith.

The trim()open in new window method removes whitespace from the beginning and the end of a string. In this context, whitespace refers to all the whitespace characters including: spaces, tabs and returns.

const greeting = '    Hello, World!     ';

// removing all whitespace from string
console.log(greeting.trim()) // 'Hello, World!'

Also see trimStart()open in new window and trimEnd()open in new window for alternative methods of removing whitespace from a string.