string methods code example

Example 1: js string methods

JS String Methods:
charAt()
Returns a character at a specified position inside a string
charCodeAt()
Gives you the unicode of character at that position
concat()
Concatenates (joins) two or more strings into one
fromCharCode()
Returns a string created from the specified sequence of UTF-16 code units
indexOf()
Provides the position of the first occurrence of a specified text within a string
lastIndexOf()
Same as indexOf() but with the last occurrence, searching backwards
match()
Retrieves the matches of a string against a search pattern
replace()
Find and replace specific text in a string
search()
Executes a search for a matching text and returns its position
slice()
Extracts a section of a string and returns it as a new string
split()
Splits a string object into an array of strings at a specified position
substr()
Similar to slice() but extracts a substring depended on a specified number of characters
substring()
Also similar to slice() but can’t accept negative indices
toLowerCase()
Convert strings to lowercase
toUpperCase()
Convert strings to uppercase
valueOf()
Returns the primitive value (that has no properties or methods) of a string object

Example 2: methods in python

#Objects can also contain methods. Methods in objects are functions that belong to the object.
#Let us create a method in the Person class:

class Person:
  
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self): # This is a method
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Example 3: java string methods

static String valueOf(int i) - returns the string representation of the int 
argument.

Example 4: string java

System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2,3);
     String d = cde.substring(1, 2);

Example 5: js string methods

// String methods:
'hello'.toUpperCase(); // "HELLO";
'LOL'.toLowerCase(); // "lol"
'    omg  '.trim(); // "omg"

// String methods with arguments:
// ==============================

//indexOf returns the index where the character is found (or -1 if not found)
'spider'.indexOf('i'); //2
'vesuvius'.indexOf('u'); //3 - only returns FIRST matching index
'cactus'.indexOf('z'); //-1 not found

// slice - returns a "slice" of a string
"pancake".slice(3); //"cake" - slice from index 3 onwards
"pancake".slice(0, 3); //"pan" - slice from index 0 up to index 3

// replace - returns a new string, with the FIRST match replaced
"pump".replace("p", "b"); //"bump" - only replaces first "p"

// String Template Literals
// Use backtick characters, NOT SINGLE QUOTES!