Javascript string important methods – part-1

Strings are useful for holding data that can be represented in text form.

String is a datatype which store text that can be number, letter, symbol emoji or any symbol or punctuation.

"Hi I am 28 years old"
"I Love to 😊 :-)"

JavaScript makes no distinction between single-quoted strings and double-quoted strings.

We can use single-quote (‘) within double-quoted string and double-quote (“) can be used in single-quoted string.

"Hi my name is 'singhak'"
'Hi, what is your "name" ?'

Even we can use single-quote within single-quote and double-quote within double-quote using backslash to escape the quotation marks.

"Hi my name is "singhak"!"
'Hi my name is 'singhak'!'

Properties and Methods:

1. length:

length is properties of string that is used to calculate the number of character in a string. While counting number of characters it also considers whitespace also.

var str = "Hello India"
console.log(str.length) // 11

2. slice:

The slice() method extracts a section/part of a string and returns it as a new string, without modifying the original string.

str.slice(beginIndex[, endIndex])

If beginIndex is greater than or equal to str.length, slice() returns an empty string.

let str = 'The morning is upon us.'
str.slice(22) // ""

slice() extracts up to but not including endIndex. str.slice(1,4) extracts the second character through the fourth character (characters indexed 1, 2, 3).

const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

Using slice() with negative indexes:

If negative, it is treated as str.length + beginIndex. (For example, if beginIndex is -3 it is treated as str.length – 3.)

let str = 'Hello World'
str.slice(-3)      // returns 'rld.'
str.slice(-3, -1)  // returns 'ld'
str.slice(0, -1)   // returns 'Hello Worl'

Representation of negative indexing:

Hello World 
012345678910+ve indexing
-11-10-9-8-7-6-5-4-3-2-1-ve indexing
let str = 'morning is good'
str.slice(-5, -1) // "goo"

3. split:

The split() returns an array of the sub-string based on separator.

str.split([separator[, limit]])

grapheme cluster is a sequence of one or more Unicode code points that should be treated as a single unit by various processes:

If separator is not pass in split(), the returned array contains one element consisting of the entire string.

"Hello World".split() // ["Hello World"]

If separator contains multiple characters, that entire character sequence must be found in order to split.

let str = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
str.split(',;') // ["Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"]
// as above separator - ",;" is not found in given string so did not split

str = "Jan,;Feb,;Mar,;Apr,;May,;Jun"
str.split(',;') // ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

If separator is an empty string (“”), str is converted to an array of each of its UTF-16 “characters”

"Hello".split("") // ["H", "e", "l", "l", "o"]

// but it will not work properly in string contains user-perceived characters (grapheme clusters) or Unicode characters (codepoints)

'𝟘𝟙𝟚𝟛'.split('') // ["�", "�", "�", "�", "�", "�", "�", "�"]
"I💖U".split('') //  ["I", "�", "�", "U"]

There is one more parameter in split() that is limit. If it is provided then it will return split array till a limit.

let str = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
str.split(',', 2) // ["Jan", "Feb"]
// Here we gave limit 2 so it will array upto length 2

str.split(',',0) // []

// if the array may contain fewer entries than limit than it will return entire array
str.split(',',25) // ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

Splitting with a RegExp:

the separator can be a regular expression

const myString = 'Hello 1 word. Sentence number 2.'
// regular expresion for spliting on any digit
const rex = /d/ 
myString.split(rex) // ["Hello ", " word. Sentence number ", "."]

4. startsWith:

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

str.startsWith(searchString[, position])
const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// expected output: true

console.log(str1.startsWith('Sat', 3));
// expected output: false
const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// expected output: true

console.log(str1.startsWith('sat'));
// expected output: false

This method also takes an optional argument position. With this, we can tell this method from where it should start to check string

let str = 'To be, or not to be, that is the question.'

console.log(str.startsWith('To be'))          // true
console.log(str.startsWith('not to be'))      // false
// In above it is giving false but when we will give position from where it need to start then it will give true
console.log(str.startsWith('not to be', 10))  // true

Similarly, there is a method endsWith() that determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

5. valueOf:

The valueOf() method returns the primitive value of a String object.

str.valueOf()
const stringObj = new String("foo");

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.valueOf());
// expected output: "foo"

We can create a string using two ways, but underlying both are different. One is a primitive string and the other is Object.

S = new String("singhak")
s = "singhak"
s === S // false
typeof(s) // "string"
typeof(S) // "object"

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Properties

Leave a Reply