String
Working With Strings
methods
Return new strings
.length
.indexOf()
1
2
3const airline = 'TAP Air Portugal';
console.log(airline.indexOf('Portugal'));//8
console.log(airline.indexOf('portugal'));//-1
Case sensetive*
.lastIndexOf()
1
2const airline = 'TAP Air Portugal';
console.log(airline.lastIndexOf('r'));//10The last ‘r’.
.slice()
1
2
3
4const airline = 'TAP Air Portugal';
console.log(airline.slice(4));//Air Portugal
console.log(airline.slice(4, 7));//Air
console.log(airline.slice(-2));//alIt 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.
.toLowerCase()
.toUpperCase()
.trim()
.replace()
You can use regular expression here.
1
console.log(airline.replaceAll(/A/g, 'a'));//TaP air Portugal
It replaced all ‘A’.
.replaceAll()
.repeat()
1
2
3
4const planesInLine = function (n) {
console.log(`There are ${n} planes in line ${'✈️'.repeat(n)}`);
};
planesInLine(10);//There are 10 planes in line ✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️
Return booleans.
- .includes()
- .startsWith()
- 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 | console.log(typeof new String('aniya')); //object |
Other important method:split() join()
- split()
1 | const str = 'qwer+zxcv+ajf0s+sjaf'; |
- join()
Input an array,return a string.
1 | const str = 'qwer+zxcv+ajf0s+sjaf'; |
Padding Methods
padStart()
1
2const str = 'qwer+zxcv+ajf0s+sjaf';
console.log(str.padStart(30, ')+'));//)+)+)+)+)+qwer+zxcv+ajf0s+sjafpadEnd()
1
2const str = 'qwer+zxcv+ajf0s+sjaf';
console.log(str.padEnd(30, ')+'));//qwer+zxcv+ajf0s+sjaf)+)+)+)+)+