String

Working With Strings

methods

  1. Return new strings

    1. .length

    2. .indexOf()

      1
      2
      3
      const airline = 'TAP Air Portugal';
      console.log(airline.indexOf('Portugal'));//8
      console.log(airline.indexOf('portugal'));//-1

    Case sensetive*

    1. .lastIndexOf()

      1
      2
      const airline = 'TAP Air Portugal';
      console.log(airline.lastIndexOf('r'));//10

      The last ‘r’.

    2. .slice()

      1
      2
      3
      4
      const airline = 'TAP Air Portugal';
      console.log(airline.slice(4));//Air Portugal
      console.log(airline.slice(4, 7));//Air
      console.log(airline.slice(-2));//al

      It returns a new string.

      The end value is not included in the new string.

      When the argument is negative, it will count from the end.

    3. .toLowerCase()

    4. .toUpperCase()

    5. .trim()

    6. .replace()

      You can use regular expression here.

      1
      console.log(airline.replaceAll(/A/g, 'a'));//TaP air Portugal

      It replaced all ‘A’.

    7. .replaceAll()

    8. .repeat()

      1
      2
      3
      4
      const planesInLine = function (n) {
      console.log(`There are ${n} planes in line ${'✈️'.repeat(n)}`);
      };
      planesInLine(10);//There are 10 planes in line ✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️
  2. Return booleans.

    1. .includes()
    2. .startsWith()
    3. endsWith()

We do know that string is a type of primitives,why it has methods?

Because javascript automaticlly will turn the string into an object,and when the operation is done, it will turn back into a string primitive.

So all string methods return primitives, even if called on a string object.

1
2
console.log(typeof new String('aniya')); //object
console.log(typeof new String('aniya').slice(-1));//string

Other important method:split() join()

  1. split()
1
2
const str = 'qwer+zxcv+ajf0s+sjaf';
console.log(str.split('+'));//[ 'qwer', 'zxcv', 'ajf0s', 'sjaf' ]
  1. join()

​ Input an array,return a string.

1
2
3
const str = 'qwer+zxcv+ajf0s+sjaf';
const strSplit = str.split('+');
console.log(strSplit.join('---'));//qwer---zxcv---ajf0s---sjaf

Padding Methods

  1. padStart()

    1
    2
    const str = 'qwer+zxcv+ajf0s+sjaf';
    console.log(str.padStart(30, ')+'));//)+)+)+)+)+qwer+zxcv+ajf0s+sjaf
  2. padEnd()

    1
    2
    const str = 'qwer+zxcv+ajf0s+sjaf';
    console.log(str.padEnd(30, ')+'));//qwer+zxcv+ajf0s+sjaf)+)+)+)+)+

本站由 @Eureka 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。