String

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

String:

String is sequence of characters enclosed withing the pair of double quotation or single quotation
marks.

String are object within javascript language

Ex:

‘abc’,

“xyz”,

“78TT$”

Creating string / Declaring String/ Defining String

In javascript string is created using two ways

1. Using literal
2. By String Object (Using new keyword)

1. Using Literal
String literal is created by using single quote or double quote

Syntax:

var string_name=’string_value’;
or
var string_name=”string_value”;

example

<html>
<head>
<title>String Example</title>
</head>
<body>
<script>
var string1="samarth";
document.write(string1);
document.write("<br>");
var string2='samarth';
document.write(string2);

</script>
</body>
</html>

2. By String Object (Using new keyword)

new keyword is used to create the string instance

syntax:

var string_name=new String(“string_value”);

example

<html>

<head>

<title>String Example</title>

</head>

<body>

<script>

var string1=new String("samarth");

document.write(string1);

document.write("<br>");

var string2=new String('samarth');

document.write(string2);

</script>

</body>

</html>

//output

samarth
Samarth

Manipulating String

String are object within javascript language

Built-in function must be used manipulate string

String methods
1. charAt(): The charAt() method in JavaScript is used to retrieve the character at a
specified index in a string.
2. charCodeAt(): Returns the Unicode of the character at a specified index in a string.
3. concat(): Combines two or more strings and returns a new string.
4. indexOf(): Returns the index of the first occurrence of a specified value in a string.
5. lastIndexOf(): Returns the index of the last occurrence of a specified value in a string.
6. search(): Searches a string for a specified value and returns the position of the match.
7. match(): Retrieves the matches of a string against a regular expression.
8. replace(): Searches a string for a specified value or a regular expression, and returns a
new string with the value(s) replaced.
9. substr(): Extracts a part of a string, beginning at a specified index and extending for a
given number of characters.
10. substring(): Extracts the characters from a string between two specified indices.
11. slice(): Extracts a section of a string and returns it as a new string.
12. toLowerCase(): Converts a string to lowercase letters.
13. toUpperCase(): Converts a string to uppercase letters.
14. split(): Splits a string into an array of substrings using a specified separator.
15. trim(): Removes whitespace from both ends of a string.
16. toString(): converting number to string

Joining string
concat()

concat() method is used to combines two or more strings and returns a new string.

Syntax:

str.concat(string2, string3, ..., stringN);

example

<html>
<head>
<title>Concat Example</title>
<script>
function concatenateStrings() {
let str1 = "Hello, ";
let str2 = "world!";
let result = str1.concat(str2);
document.write(result);
}
</script>
</head>
<body>
<script>
concatenateStrings();
</script>
</body>
</html>

//output
Hello, world!

Retrieving character from given position


The charAt() method in JavaScript is used to retrieve the character at a specified index in a
string.
Syntax:
string.charAt(index)
 string: The string from which the character will be extracted.
 index: The position of the character to return. The index starts at 0.

<html>
<head>
<title>charAt() Example</title>
<script>
function displayCharacter() {
let str = "Hello, world!";
let char = str.charAt(7);
document.write("The character at index 7 is: " + char);
}
</script>
</head>
<body>
<script>
displayCharacter();
</script>
</body>
</html>

//output
The character at index 7 is: w

Retrieves the position of character in string


indexOf():
The indexOf() method returns the index of the first occurrence of a specified value in a string.
If the value is not found, it returns -1.

Syntax:
string.indexOf(searchValue, start)
 string: The string in which to search.
 searchValue: The value to search for within the string.
 start (optional): The position in the string at which to start the search. Default is 0.

<html>
<head>
<title>indexOf() Example</title>
<script>
function findIndexOf() {
let str = "Hello, world!";
let index = str.indexOf("o");
document.write("The first occurrence of 'o' is at index: " + index);
}
</script>
</head>
<body>
<script>
findIndexOf();
</script>
</body>
</html>
//Output
The first occurrence of 'o' is at index: 4

lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified value in a
string. If the value is not found, it returns -1.
Syntax:
string.lastIndexOf(searchValue, start);
 string: The string in which to search.
 searchValue: The value to search for within the string.
 start (optional): The position in the string at which to start the search backward. Default is
str.length - 1.
Example
<html>
<head>
<title>lastIndexOf() Example</title>
<script>
function findLastIndexOf() {
let str = "Hello, world!";
let index = str.lastIndexOf("o");
document.write("The last occurrence of 'o' is at index: " + index);
}
</script>
</head>
<body>
<script>
findLastIndexOf();
</script>
</body>
</html>

//output
The last occurrence of 'o' is at index: 8

Dividing Text
The split() method divides a string into an array of substrings based on a specified separator
and returns the new array.
Syntax:
string.split(separator, limit)
 string: The string to be split.
 separator: Specifies the character(s) to use for splitting the string. If omitted, the entire
string is returned as a single element array.
 limit (optional): An integer that specifies the number of splits to be found.

Example
<html>
<head>
<title>split() Example</title>
<script>
function splitString() {
let str = "Welcome to JavaScript.";
let words = str.split(" ");
document.write("<b>words are: </b>" + words.join(", "));
}
</script>
</head>
<body>
<script>
splitString();
</script>
</body>
</html>

//output
words are: Welcome, to, JavaScript.

Changing the case of String

1. toUpperCase()

The toUpperCase() method converts all the characters in a string to uppercase


letters.

Syntax:

string.toUpperCase()

 string: The string to be converted to uppercase.

<html>
<head>
<title>toUpperCase() Example</title>
<script>
function convertToUpperCase() {
let str = "Hello, world!";
let upperStr = str.toUpperCase();
document.write("The uppercase string is: " + upperStr);
}
</script>
</head>
<body>
<script>
convertToUpperCase();
</script>
</body>
</html>

//output
The uppercase string is: HELLO, WORLD!
toLowerCase()

The toLowerCase() method converts all the characters in a string to lowercase letters.

Syntax:

string.toLowerCase()

string: The string to be converted to lowercase.

Example

<html>
<head>
<title>toLowerCase() Example</title>
<script>
function convertToLowerCase() {
let str = "Hello, WORLD!";
let lowerStr = str.toLowerCase();
document.write("The lowercase string is: " + lowerStr);
}
</script>
</head>
<body>
<script>
convertToLowerCase();
</script>
</body>
</html>

Output

The lowercase string is: hello, world!

Copying Substring

1. substring()
The substring() method in JavaScript is used to extract a part of a string and
return it as a new string, without modifying the original string.
syntax

string.substring(startIndex, endIndex);

returns substring from startIndex to endIndex-1.

endIndex is optional, if it is not given the fetch substring from start index to
end of the string

if either indexStart or indexEnd is negative, they are treated as 0

<html>

<head>

<title>String Substring Example</title>

</head>

<body>

<script>

let str = "Hello, World!";

let hello = str.substring(0, 5);

document.write( hello + "<br>"); // Output: Hello

let world = str.substring(7, 12);

document.write(world + "<br>"); // Output: World

let toEnd = str.substring(7);

document.write(toEnd + "<br>"); // Output: World!

let swapped = str.substring(12, 7);

document.write(swapped + "<br>"); // Output: World

let outOfBounds = str.substring(7, 50);


document.write(outOfBounds + "<br>"); // Output: World!

</script>

</body>

</html>

Output

Hello
World
World!
World
World!

2. slice()

The slice() method in JavaScript is used to extract a part of a string and return it
as a new string, without modifying the original string.

It allows for both positive and negative indices to specify the start and end of
the slice.

Syntax:

string.slice(beginIndex, endIndex);

returns substring from startIndex to endIndex-1.

endIndex is optional, if it is not given the fetch substring from start index to end of the
string

beginIndex: The index at which to start the slice (inclusive). If negative, it is counted from
the end of the string.

endIndex: The index at which to end the slice (exclusive). If omitted or greater than the
string length, it slices to the end of the string. Negative values are also counted from the end.
<html>

<head>

<title>String Slice Example</title>

</head>

<body>

<script>

let str = "Hello, World!";

// Extract "Hello"

let hello = str.slice(0, 5);

document.write("Hello: " + hello + "<br>"); // Output: Hello

// Extract "World"

let world = str.slice(7, 12);

document.write("World: " + world + "<br>"); // Output: World

// Extract from index 7 to the end of the string

let toEnd = str.slice(7);

document.write(toEnd + "<br>"); // Output: World!

// Extract using negative indices

let negativeIndices = str.slice(-6, -1);

document.write("negativeIndices + "<br>"); // Output: World

// Slice beyond the end of the string

let outOfBounds = str.slice(7, 50);

document.write(outOfBounds + "<br>"); // Output: World!

</script>
</body>

</html>

Output

Hello: Hello

World: World

World!

negativeIndices

World

World!

//Difference between substring() and slice()

substring() slice()
If startIndex is greater than endIndex, the If startIndex is greater than endIndex, the
method swaps them. method returns an empty string.
let text = "Hello, world!"; let text = "Hello, world!";
console.log(text.substring(0, 5)); // "Hello" console.log(text.slice(0, 5)); // "Hello"
console.log(text.substring(5, 0)); // "Hello" console.log(text.slice(5, 0)); // ""

Negative indices are treated as 0. Allows negative indices to count from the
end of the string.
let text = "Hello, world!"; let text = "Hello, world!";
console.log(text.slice(5, -3)); // ", wor" console.log(text.slice(-6)); // "world!"
substr():

The substr() method in JavaScript is used to extract a part of a string and return
it as a new string, without modifying the original string.

Syntax:

string.substr(startIndex, length);

startIndex: The index at which to begin extraction. If negative, it counts from the end of the
string.

length (optional): The number of characters to extract. If omitted, extracts to the end of the
string.

Example

<html>

<head>

<title>String Substr Example</title>

</head>

<body>

<script>

let str = "Hello, World!";

let hello = str.substr(0, 5);

document.write(hello + "<br>"); // Output: Hello

let world = str.substr(7, 5);

document.write(world + "<br>"); // Output: World

let toEnd = str.substr(7);

document.write(toEnd + "<br>"); // Output: World!


let fromEnd = str.substr(-6, 5);

document.write(fromEnd + "<br>"); // Output: World

let outOfBounds = str.substr(7, 50);

document.write(outOfBounds + "<br>"); // Output: World!

</script>

</body>

</html>

//Output

Hello
World
World!
World
World!

Converting String to Number

1.parseInt()

It is used to convert numeric string into integer.

Syntax:

parseInt(string, radix)

string: The string to be parsed. If the string does not start with a numeric value,
parseInt() will return NaN.

radix (optional): represents the base of the numeral system to be used. For
example, a radix of 10 represents the decimal system, 16 represents
hexadecimal, etc.
<html>

<head>

<title>parseInt Examples</title>

</head>

<body>

<script>

// Store results in variables

let num1 = parseInt("42");

let num2 = parseInt("0xF", 16);

let num3 = parseInt("1010", 2);

let num4 = parseInt("007", 8);

let num5 = parseInt("123abc");

let num6 = parseInt("abc123");

// Print the results using document.write()

document.write("Decimal (42): " + num1 + "<br>");

document.write("Hexadecimal (0xF, base 16): " + num2 + "<br>");

document.write("Binary (1010, base 2): " + num3 + "<br>");

document.write("Octal (007, base 8): " + num4 + "<br>");

document.write("String with numbers (123abc): " + num5 + "<br>");

document.write("Invalid parsing (abc123): " + num6 + "<br>");

</script>

</body>
</html>

Output

Decimal (42): 42

Hexadecimal (0xF, base 16): 15

Binary (1010, base 2): 10

Octal (007, base 8): 7

String with numbers (123abc): 123

Invalid parsing (abc123): NaN

Number()

In JavaScript, Number() is a function used to convert a given value to a number.


Syntax:

Number(value)

 value: The value to be converted to a number.

It can convert strings, booleans, and other types to numbers, and it returns

NaN (Not a Number) if the conversion isn't possible.

 If the value is a number, it is returned as-is.


 If the value is a boolean, true converts to 1 and false converts to 0.
 If the value is a string:
 If the string contains a valid numeric value, it is converted to that number.
 If the string is empty or contains only whitespace, it converts to 0.

 If the string cannot be converted to a number, it returns NaN.

 null converts to 0.
 undefined converts to NaN.
<html>
<head>
<title>Number() Examples</title>
</head>
<body>
<script>
let num1 = Number("42");
let num2 = Number(true);
let num3 = Number(false);
let num4 = Number(" 123 ");
let num5 = Number("");
let num6 = Number("abc123");
let num7 = Number(null);
let num8 = Number(undefined);

document.write("String '42': " + num1 + "<br>");


document.write("Boolean true: " + num2 + "<br>");
document.write("Boolean false: " + num3 + "<br>");
document.write("String ' 123 ': " + num4 + "<br>");
document.write("Empty string '': " + num5 + "<br>");
document.write("Invalid string 'abc123': " + num6 + "<br>");
document.write("Null: " + num7 + "<br>");
document.write("Undefined: " + num8 + "<br>");
</script>
</body>
</html>
Example
String '42': 42
Boolean true: 1
Boolean false: 0
String ' 123 ': 123
Empty string '': 0
Invalid string 'abc123': NaN
Null: 0
Undefined: NaN

toString()
The toString() method in JavaScript converts a number, object, or other data types to a
string.
Syntax:
value.toString([radix])

value: The value you want to convert to a string.


radix (optional, for numbers only): base to use for representing numeric values. If
omitted, the base 10 is used.
<html>
<head>
<title>toString() Examples</title>
</head>
<body>
<script>
// Number to string
let num = 42;
let numStr = num.toString();
document.write("Number to string: " + numStr + "<br>");

// Number to binary string


let binaryStr = num.toString(2);
document.write("Number to binary string: " + binaryStr + "<br>");

// Boolean to string
let bool = true;
let boolStr = bool.toString();
document.write("Boolean to string: " + boolStr + "<br>");

// Object to string
let obj = {name: "Alice", age: 30};
let objStr = obj.toString();
document.write("Object to string: " + objStr + "<br>");

// Array to string
let arr = [1, 2, 3];
let arrStr = arr.toString();
document.write("Array to string: " + arrStr + "<br>");
</script>
</body>
</html>

Output
Number to string: 42
Number to binary string: 101010
Boolean to string: true
Object to string: [object Object]
Array to string: 1,2,3

 fromCharCode()
The String.fromCharCode() method in JavaScript creates a string from one or more
Unicode values.
Syntax:
String.fromCharCode(num1, num2, ..., numN);

num1, num2, ..., numN:


A list of Unicode values (integers) to convert to characters. Each value should be between
0 and 65535.
The String.fromCharCode() method takes one or more Unicode values and returns a
string containing the characters represented by those values.

Example
<html>
<head>
<title>String.fromCharCode() Example</title>
</head>
<body>

<script>
// Single Unicode value
let char1 = String.fromCharCode(65);
document.write("Char1: " + char1 + "<br>");

// Multiple Unicode values


let char2 = String.fromCharCode(72, 101, 108, 108, 111);
document.write("Char2: " + char2 + "<br>");

// Mixed Unicode values


let char3 = String.fromCharCode(67, 111, 100, 101, 32, 81, 117, 101, 101, 110);
document.write("Char3: " + char3 + "<br>");
</script>

</body>
</html>
Output:
Char1: A
Char2: Hello
Char3: Code Queen

You might also like