DEV Community

Frugence Fidel
Frugence Fidel

Posted on • Updated on

10 JavaScript string methods you should know

This post is originally published to my blog.

In this post I will summarize 10 javascript string methods you should at least known according to me.

If interested read here 10 javascript array methods you should know
.

String is anything inside single or double quotes.

Here are 10 javascript string methods you should know.

1. startsWith()

Check if string starts with specified character(s).

  const str = 'JavaScript is amazing';

  console.log(str.startsWith('JavaScript')); // true
  console.log(str.startsWith('Java')); // true
  console.log(str.startsWith('javascript')); // false

  // position is optional
  // if not specified, the default value is 0
  console.log(str.startsWith('Script', 4)); // true
  console.log(str.startsWith('SCRIPT', 4)); // false
Enter fullscreen mode Exit fullscreen mode

2. endsWith()

Check if string ends with specified character(s).

  const str = 'JavaScript is amazing';

  // check if ends with 'amazing'
  console.log(str.endsWith('amazing')); // true
  console.log(str.endsWith('ing')); // true
  console.log(str.endsWith('Amazing')); // false

  // length is optional
  // if not specified, the default value is length of the string
  console.log(str.endsWith('is', 13)); // true
  console.log(str.endsWith('i', 13)); // false
  console.log(str.endsWith('s', 13)); // true
Enter fullscreen mode Exit fullscreen mode

3. includes()

Check if string contains specified character(s).

  const str = 'JavaScript is amazing';

  console.log(str.includes('Script')); // true
  console.log(str.includes('script')); // false
  console.log(str.includes(' ')); // true
  console.log(str.includes('array')); // false
Enter fullscreen mode Exit fullscreen mode

4. slice()

Copy some part of string without modifying the original one.

  const str = 'JavaScript is amazing';

  // Default start index is 0
  console.log(str.slice()); // 'JavaScript is amazing'

  // start copy at index 4
  console.log(str.slice(4)); // 'Script is amazing'

  // end copy at index 10(character at this index will not be included)
  console.log(str.slice(0, 10)); // 'JavaScript'
Enter fullscreen mode Exit fullscreen mode

5. toUpperCase()

Convert string into upper case.

  const str = 'JavaScript is amazing';

  console.log(str.toUpperCase()); // 'JAVASCRIPT IS AMAZING'
Enter fullscreen mode Exit fullscreen mode

6. toLowerCase()

Convert string into lower case.

  const str = 'JavaScript is amazing';

  console.log(str.toLowerCase()); // 'javascript is amazing'
Enter fullscreen mode Exit fullscreen mode

7. charAt()

Return character at specified position.

  const str = 'JavaScript is amazing';

  console.log(str.charAt()); // 'J'
  console.log(str.charAt(11)); // 'i'
  console.log(str.charAt(14)); // 'a'
  console.log(str.charAt(110)); // ''
Enter fullscreen mode Exit fullscreen mode

8. split()

Split string into array of substrings.

  const str = 'JavaScript is amazing';
  const strNew = 'JavaScript-is-amazing';

  console.log(str.split()); // ["JavaScript is amazing"]

  // Separator string used to determine where to make each split
  console.log(str.split('S')); // ["Java", "cript is amazing"]
  console.log(str.split('is')); // ["JavaScript ", " amazing"]
  console.log(str.split(' ')); // ["JavaScript", "is", "amazing"]
  console.log(strNew.split('-')); // ["JavaScript", "is", "amazing"]
Enter fullscreen mode Exit fullscreen mode

9. replace()

Replaces specified value with another value in a string.

  const str = 'JavaScript is amazing';

  console.log(str.replace('JavaScript', 'Node.js')); // 'Node.js is amazing'

  // replace() method is case sensitive
  // replace will not work
  console.log(str.replace('Javascript', 'Node.js')); // 'JavaScript is amazing'

  // use regular expression for case insensitive
  console.log(str.replace(/Javascript/i, 'Node.js')); // 'Node.js is amazing'

  // replace() method replaces only the first match
  console.log(str.replace('a', 'A')); // 'JAvaScript is amazing'

  // to replace all matches, use regular expression
  console.log(str.replace(/a/g, 'A')); // 'JAvAScript is AmAzing'
Enter fullscreen mode Exit fullscreen mode

10. repeat()

Return new string with specified number of copies of existing string.

  const str = 'JavaScript';

  console.log(str.repeat(3)); // 'JavaScriptJavaScriptJavaScript'
  console.log(str.repeat(1)); // 'JavaScript'
  console.log(str.repeat(0)); // ''
Enter fullscreen mode Exit fullscreen mode

Top comments (14)

Collapse
 
itsasine profile image
ItsASine (Kayla)

repeat exists? :o

I've been doing new Array(52).join('a'); to make a string of 52 as, but I could have just used 'a'.repeat(52)... now I need to make a little commit to update that.

The other day I even ranted about how nice Python's 'a' * 52 would have been.

Collapse
 
frugencefidel profile image
Frugence Fidel • Edited

They are not same

 const first = new Array(2).join('a');
 console.log(first); // 'a'

 const second = 'a'.repeat(2);
 console.log(second); // 'aa'

 // new Array(52).join('a') will not print 52 a's, print 51 a's
 const aLength = new Array(52).join('a').length;
 console.log(aLength); // 51
Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited

Oops, you're right! Typo on my part :) For the sake of my E2E tests, I actually think repeat would be easier to read.

it('displays an error for too many characters', function() {
    relevantPage.middleInitial.sendKeys('a'.repeat(2)); // clearly shows that 2 is considered too many

    expect(relevantPage.middleInitialTooLongMessage.getText()).toEqual('Middle initial is too long');
});
Thread Thread
 
frugencefidel profile image
Frugence Fidel

Actually repeat is easy to read

If you want to make string of 52 a's with repeat is so easy

  const a = 'a'.repeat(52);
  console.log(a); // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  console.log(a.length); // 52
Thread Thread
 
siddharthray profile image
siddharthray

Array index starts from 0 which means it will print 52 times.

Thread Thread
 
diek profile image
diek

Yass, and since join acts as 'glue', using 'a' as glue for 52 nothings will print 'a' 51 times. Give it a try ;)

Collapse
 
patrickcole profile image
Patrick Cole

Great list of methods for Strings. I would just like to highlight that String.startsWith() and String.repeat() are ES2015+ String.endsWith() is ES6+, so polyfill accordingly to support edge cases.

Collapse
 
waldbach profile image
Janne Wolterbeek

Thanks, was wondering about that!

Collapse
 
dankwansere profile image
Dankwansere

Very useful, Thanks!

Collapse
 
kleinetigervk profile image
Lorna Roberts

Thanks for this!

Collapse
 
tetyemez profile image
Tugrul

Hi, thanks for the update. What about substr() function. Is it necessary when slice() exist?

Collapse
 
frugencefidel profile image
Frugence Fidel • Edited

substr() is not part of the core JavaScript language and may be removed in the future. Use slice() or substring() instead

Collapse
 
jenc profile image
Jen Chan

I'm not sure whether this one is deprecated or maybe I read that incorrectly...

Collapse
 
safinghoghabori profile image
Safin Ghoghabori

Can you tell me real world use case of reapeat() method? Idk why we need it 🤔

Thanks in advance!