A string
is a sequence characters that may consist of letters, numbers, or symbols like “John Doe”. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.
There are 3 possible ways to check whether a string exists or not:
A) Using indexOf
: You can use String.prototype.indexOf
which returns the index of a substring if found otherwise return -1.
var str1='If you think this has a happy ending, you haven’t been paying attention.'; console.log(str1.indexOf('you')); // output : 3 console.log(str1.indexOf('we')); // output : -1
B) Using includes : You can use String.prototype.includes
which returns true if found otherwise return false.
var str1='If you think this has a happy ending, you haven’t been paying attention.'; console.log(str1.includes('you')); // output: true console.log(str1.includes('we')); // // output: false
C) Using regex : Using Regular expression's test method(RegExp.test), return true if test method passes otherwise false
var regex =/you/; var regex1 =/we/; var str1='If you think this has a happy ending, you haven’t been paying attention.'; console.log(regex.test(str1)); // output: true console.log(regex1.test(str1)); // output: false
There are server ways to get the last character of a string and some of them are as follows:
A) Using bracket notation
var str1='If you think this has a happy ending, you haven’t been paying attention'; var lastChar = str1[str1.length - 1]; console.log(lastChar); // output : n
B) charAt[index]
var str1='If you think this has a happy ending, you haven’t been paying attention'; var lastChar =str1.charAt(str1.length -1); console.log(lastChar); // output : n
C) substring
var str1='If you think this has a happy ending, you haven’t been paying attention'; var lastChar =str1.substring(str1.length -1); console.log(lastChar); // output : n
D) using slice
var str1='If you think this has a happy ending, you haven’t been paying attention'; var lastChar =str1.slice(-1); console.log(lastChar); // output : n
E) Using lambda expression
var str1='If you think this has a happy ending, you haven’t been paying attention'; const getLastChar = (x) => x.split('').reverse().join(',').replace(',', '')[x.length === x.length + 1 ? 1 : 0]; var result = getLastChar(str1) console.log(result); // output : n
A) Using slice
var str1='If you think this has a happy ending, you haven’t been paying attention'; var result= str1.slice(-2); console.log(result); // output : on
B) Using substr()
var str1='If you think this has a happy ending, you haven’t been paying attention'; var result =str1.substr(-2); console.log(result); // output : on
C) Using substrig()
var str1='If you think this has a happy ending, you haven’t been paying attention'; var result = str1.substring(str1.length-2, str1.length) console.log(result); // output : on
var str1 ='1234 Hello JavaScript 56789'; let regex = /[a-z]/gi; var result = str1.replace(regex, ''); console.log(result); // output : 1234 56789
For example : input : abcab , output : c
function removeDuplicateChar(str) { var retVal = ''; if (str && str.length > 0) { // for (let index = 0; index < str.length; index++) { // if first and and last index are same then there is no duplicate charter if (str.indexOf(str[index]) == str.lastIndexOf(str[index])) { retVal += str[index]; } } } return retVal; } console.log(removeDuplicateChar('abcab')); // Output : c console.log(removeDuplicateChar('123412')); // output : 34
A) Using loop
var str1='If you think this has a happy ending, you haven’t been paying attention'; function chartCount(str) { let retVal = {}; for(let i = 0; i < str.length; i++) { const currentLetter = str.charAt(i); retVal[currentLetter] = retVal[currentLetter] + 1 || 1; } return retVal; } var result =chartCount(str1); console.log(result);
B) Using reduce
var str1='If you think this has a happy ending, you haven’t been paying attention'; function chartCountUsingReduce(str) { return str.split("").reduce((a, letter) => { a[letter] = (a[letter] || 0) + 1; return a; }, {}); } var result1 =chartCountUsingReduce(str1); console.log(result1);
You can use string replace method to replace the all the occurrences in string.
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
A) Using searchValue and newValue
var str1='If you think this has a happy ending, you haven’t been paying attention'; var result = str1.replace('this','that'); console.log(result);
B) Using Regex
var str1='If you think this has a happy ending, you haven’t been paying attention'; var regex=/this/g; var result1 = str1.replace(regex,'that') console.log(result1);
C) Using Split
attention'; var result2 = str1.split('this').join('that'); console.log(result2);
A) using split
var str1='John Doe' str1 = str1.split(""); //convert the string to array str1 = str1.reverse(); // revers the array str1 = str1.join(""); //then join the reverse order values together console.log(str1); // output : eoD nhoJ
B) using for loop increment
function reverseStringUsingLoopIncrement(str){ let retVal =""; for(let i= 0; i
C) using for loop decrement
function reverseStringUsingLoopDecrement(str){ let retVal = ""; for(let i = str.length-1; i>=0; i--){ retVal = retVal+ str[i]; } return retVal; } var str1='John Doe' var result = reverseStringUsingLoopDecrement(str1) console.log(result);
D) Using for-of loop
function reverseStringUsingForOfLoop(str){ let retval =""; for(let char of str){ retval = char + retval; } return retval; } var str1='John Doe' var result = reverseStringUsingForOfLoop(str1) console.log(result); // output : eoD nhoJ
E) Using foreach loop
function reverseStringUsingForeachLoop(str){ let retVal = ""; str.split("").forEach(function(char){ retVal = char + retVal; }); return retVal; } var str1='John Doe' var result = reverseStringUsingForeachLoop(str1) console.log(result); // output : eoD nhoJ
F) using ES6
function reverseStringUsingES6(str) { let retVal = ""; str.split("").forEach(ch => retVal = ch + retVal); return retVal; } var str1 = 'John Doe' var result = reverseStringUsingES6(str1) console.log(result); // output : eoD nhoJ
E) using reduce
function reverseStringUsingReduce(str) { return str.split("").reduce(function (retVal, char) { return char + retVal; }, ""); } var str1 = 'John Doe' var result = reverseStringUsingReduce(str1) console.log(result); // output : eoD nhoJ
F) Using Recursion
function reverseStringUsingRecursion(str){ return str ? reverseStringUsingRecursion(str.substr(1)) + str[0] : str; }; var str1 = 'John Doe' var result = reverseStringUsingRecursion(str1) console.log(result); // output : eoD nhoJ
A) Using regex
var str = 'abcdefghijklm'; console.log(str.match(/.{1,3}/g)); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
B) using for loop
function splitStringIntoSegmentOfN(str, n) { var retVal = [] for (var i = 0, charsLength = str.length; i < charsLength; i += n) { retVal.push(str.substring(i, i + n)); } return retVal; } var str = 'abcdefghijklm'; var result = splitStringIntoSegmentOfN(str, 3); console.log(result); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
C) Using while loop
function splitStringIntoSegmentOfNUsingWhile(str, n) { let retVal = [], remaining = str; while (remaining) { let v = remaining.slice(0, n); remaining = remaining.slice(v.length); retVal.push(v); } return retVal; }; var str = 'abcdefghijklm'; var result1 = splitStringIntoSegmentOfNUsingWhile(str, 3); console.log(result1); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
D) Using ES6
function splitStringIntoSegmentOfNUsingES6(str, n) { const retVal = []; for ( const array = Array.from(str); array.length; retVal.push(array.splice(0,n).join(''))); return retVal; } var str = 'abcdefghijklm'; var result1 = splitStringIntoSegmentOfNUsingES6(str, 3); console.log(result1); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
A) using for loop
function splitStringIntoSegmentFromEndUsingLoop(str, n) { var i = str.length % n; var retVal = i ? [str.substr(0, i)] : []; for (; i < str.length; i += n) { retVal.push(str.substr(i, n)); } return retVal; } var str = 'abcdefghijklm'; var result1 = splitStringIntoSegmentFromEndUsingLoop(str, 3); console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]
B) using slice
function splitStringIntoSegmentFromEndUsingSlice(str, n) { var retVal = []; var len = str.length; while (len > 0) { len -= n; retVal.unshift(str.slice(len)); str = str.slice(0, len); } return retVal; } var str = 'abcdefghijklm'; var result1 = splitStringIntoSegmentFromEndUsingSlice(str, 3); console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]
C) using Regex
var str = 'abcdefghijklm'; var result1= str.split( /(?=(?:...)*$)/ ) console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]
You can use \\ to show the \ escape character.
var x = "John \\ Doe"; console.log(x); // output : John \ Doe var x = 'John \\ Doe'; console.log(x); // output : John \ Doe
JavaScript could be created using the newline escape character \n. This is a functionality that JavaScript inherited from the C programming language.
var str1='If you think \n this has a happy ending, \n you haven’t been \n paying attention'; console.log(str1); // output If you think this has a happy ending, you haven’t been paying attention
indexOf() method returns the position of the first occurrence of a specified value in a string.
lastIndexOf() method returns the position of the last occurrence of a specified value in a string.
var str1='If you think this has a happy ending, you haven’t been paying attention'; console.log(str1.indexOf('you')); // output : 3 console.log(str1.lastIndexOf('you')); // output : 38
search() :
indexOf() :
var str1='If you think this has a happy ending, you haven’t been paying attention'; console.log(str1.search('you')); // output : 3 var regex =/you/; console.log(str1.search(regex)); // output : 3 console.log(str1.indexOf('you',10)); // output : 38
string : String are immutable, which means, once they are created, their state can't be changed, which also makes them thread safe. String is the JavaScript String type, which you could use to create new strings.
var a = 'jd'; var b = 'jd'; console.log(a ==b); // true
a==b result will be 'true' both string reefer’s same object.
String It is parsed to a v8:StringObject (https://v8docs.nodesource.com/node-0.8/d9/d38/classv8_1_1_string_object.html )which extends Object and, apart from being a full-fledged object, serves as a wrapper for v8::String.
var x = new String("jd"); var y = new String("jd"); console.log(x ==y); //false
a==b result will be false, because they have different references.
You can make the first letter to uppercase using different ways and some of them are as follows :
A) using toUpperCase and Slice
var str1='if you think this has a happy ending, you haven’t been paying attention'; function uppercaseFirstLetter1(string) { return string[0].toUpperCase() + string.slice(1); } console.log(uppercaseFirstLetter1(str1));
B) using chartAt, toUpperCase and Slice
var str1='if you think this has a happy ending, you haven’t been paying attention'; function uppercaseFirstLetter2(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(uppercaseFirstLetter2(str1));
C) using regex
var str1='if you think this has a happy ending, you haven’t been paying attention'; function uppercaseFirstLetter3(string) { return string.replace(/^./, string[0].toUpperCase()); } console.log(uppercaseFirstLetter3(str1));
D) using prototype
var str1='if you think this has a happy ending, you haven’t been paying attention'; String.prototype.uppercaseFirstLetter4 = function() { return this.charAt(0).toUpperCase() + this.slice(1); } console.log(str1.uppercaseFirstLetter4());
E) using ES6 template string
var str1='if you think this has a happy ending, you haven’t been paying attention'; str1 = `${str1[0].toUpperCase()}${str1.slice(1)}`; console.log(str1);
F) using ES6
var str1='if you think this has a happy ending, you haven’t been paying attention'; var result = str1.replace(/^./, str => str.toUpperCase()) console.log(result);
A) Using split, map and join
function toTitleCase(str) { return str .toLowerCase() .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' '); }; var str1='if you think this has a happy ending, you haven’t been paying attention'; var result = toTitleCase(str1); console.log(result); // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
B) Using for loop
function toTitleCase1(str) { var retVal = str.toLowerCase().split(' '); for (var i = 0; i < retVal.length; i++) { var subString = retVal[i].split(''); for (var j = 0; j < subString.length; j++) { subString[0] = subString[0].toUpperCase(); } retVal[i] = subString.join(''); } return retVal.join(' '); } var str1='if you think this has a happy ending, you haven’t been paying attention'; var result = toTitleCase1(str1); console.log(result); // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
C) Using regex
function toTitleCase2(str) { return str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase()); } var str1='if you think this has a happy ending, you haven’t been paying attention'; var result = toTitleCase2(str1); console.log(result); // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
D) Using foreach
function toTitleCase3(str) { var tempArray = str.trim().toLowerCase().split(' '); var retVal = []; tempArray.forEach(function(elem, i) { retVal.push(elem.charAt(0).toUpperCase().concat(elem.substring(1))); }); return retVal.join(' '); } var str1='if you think this has a happy ending, you haven’t been paying attention'; var result = toTitleCase3(str1); console.log(result); // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
You can use String.prototype.startsWith()
method to check a string starts with specified string or not. If string start with specified string, then return true otherwise return false.
var str1 ='John Doe' console.log(str1.startsWith('John')); // output : true console.log(str1.startsWith('Doe')); // output : false
You can use String.prototype.endsWith()
method to check a string end with specified string or not. If string end with specified string, then return true otherwise return false.
var str1 ='John Doe' console.log(str1.endsWith('John')); // output : false console.log(str1.endsWith('Doe')); // output : true