String Tips
Add a word of character at a certain position in a string
If you need to insert a word or character at a certainm position in a string you can use the following snippet
var a = "Ik want Javascript tips";
var b = " the book";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
alert(output);
The spring is spliced at the sixth character, then the extra words are added and next the rest of the string is added. Alert wil show now: "I want the book Javascript tips"
If you need to insert a word or character at a certainm position in a string you can use the following snippet
var a = "Ik want Javascript tips";
var b = " the book";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
alert(output);
The spring is spliced at the sixth character, then the extra words are added and next the rest of the string is added. Alert wil show now: "I want the book Javascript tips"
Build a string with n letters
If you need to bluid a string that contains n letters you can use the next code:
var str = new Array(len + 1).join( character );
Here is an example that builds a string of 10 times the letter z
var str = new Array(10 + 1).join( "z" );
alert(str)
If you need to bluid a string that contains n letters you can use the next code:
var str = new Array(len + 1).join( character );
Here is an example that builds a string of 10 times the letter z
var str = new Array(10 + 1).join( "z" );
alert(str)
Build a string with n words
If you need to build a string that contains n times the same word you can use the next code.
var str = new Array(len + 1).join( word );
Here is an example that builds a string with 1o times the word Javascript
var str = new Array(10 + 1).join( "Javascript " );
alert(str)
If you need to build a string that contains n times the same word you can use the next code.
var str = new Array(len + 1).join( word );
Here is an example that builds a string with 1o times the word Javascript
var str = new Array(10 + 1).join( "Javascript " );
alert(str)
Change the first letter of every word in uppercase
We are going to change the first letter of each word in a string into uppercase. This can be done by splitting the words into an array, then change the first letter of each array element, annd the convert the array back into a string.
var phrase = "javascript tips by luc volders";
var phrasearray = phrase.split(" ");
var length = phrasearray.length
for (i=0; i<length; i++)
{
phrasearray[i]=phrasearray[i].charAt(0).toUpperCase() + phrasearray[i].slice(1);
}
phrase = phrasearray.join(" ");
alert(phrase);
We are going to change the first letter of each word in a string into uppercase. This can be done by splitting the words into an array, then change the first letter of each array element, annd the convert the array back into a string.
var phrase = "javascript tips by luc volders";
var phrasearray = phrase.split(" ");
var length = phrasearray.length
for (i=0; i<length; i++)
{
phrasearray[i]=phrasearray[i].charAt(0).toUpperCase() + phrasearray[i].slice(1);
}
phrase = phrasearray.join(" ");
alert(phrase);
Change the first letter in a string to uppercase
To change the first letter of a string in uppercase we use charAt(0) and change it with toUpperCase(). Next we add the rest of the string with slice()
var sentence = "javascript tips";
sentence = sentence.charAt(0).toUpperCase() + sentence.slice(1);
alert(sentence)
Convert an array into a string
It is very easy to make a string from an array.
var array = [1, 2, 3];
var teststring = array.toString();
teststring now contains: "1, 2, 3"
Convert a name into initials
To convert a full name to its initials we first split the name into its first name and surname and then we take the first letter of the firstname and convert it to uppercase and add it to a new variable. Then we do the same with the last name.
name = "Luc volders"
namesplit = naam.split(" ");
initials = namesplit[0].charAt(0).toUpperCase()
initials += namesplit[1].charAt(0).toUpperCase()
alert(initials)
To convert a full name to its initials we first split the name into its first name and surname and then we take the first letter of the firstname and convert it to uppercase and add it to a new variable. Then we do the same with the last name.
name = "Luc volders"
namesplit = naam.split(" ");
initials = namesplit[0].charAt(0).toUpperCase()
initials += namesplit[1].charAt(0).toUpperCase()
alert(initials)
Convert a string to an array
To convert a string to an array you can use the spread operator.
var teststring = "Javascript";
testarray = [...teststring];
alert (testarray);
Be aware that each character (spaces etc) will become an array element.
Convert a string to an array 2
There are 4 ways to convert a string into an array where each element is a letter from that string.
const string = 'Javascript tips';
var usingSplit = string.split('');
var usingSpread = [...string];
var usingArrayFrom = Array.from(string);
var usingObjectAssign = Object.assign([], string);
There are 4 ways to convert a string into an array where each element is a letter from that string.
const string = 'Javascript tips';
var usingSplit = string.split('');
var usingSpread = [...string];
var usingArrayFrom = Array.from(string);
var usingObjectAssign = Object.assign([], string);
Fixed length strings
There are two commands that are not very wide known called padStart and padEnd that can make life much easier. Using these commands you can easily format columns on your screen by giving strings an equal length.
Using padStart you can add an amount of letters or other characters to the beginning of your string and give the string a fixed length.
temp = String(22.5);
temp = temp.padStart(10, ".")
alert (temp);
The alert will now show ......22.5
You can exchange the "." by any other character or number of characters. The length of 10 will not be exceeded.
temp = String(5);
twmp = temp.padStart(10,"_");
alert(temp);
Alert will now show '_________5'
If you omit the character(s) the string will be filled with spaces.
padEnd does the same but adds to the end of the string.
temp = String(5);
temp = temp.padEnd(10,"*");
alert(temp);
The alert will show '5*********'
Generate a random password
Here is a quick and dirty way to generate a random password.
var password = "pw " + Math.random().toString(16).slice(2)
alert(password)
Here is a quick and dirty way to generate a random password.
var password = "pw " + Math.random().toString(16).slice(2)
alert(password)
Getting all figures in a text
The next programn gets all figures from a text. When you are building for example an IOT project you often only need the figures which can be sensor values.
let test = "temperature is 25 degrees"
let testnew = ""
for (let i=0; i<test.length; i++)
{
if (+(test[i]))
{
testnew = testnew + test[i];
}
}
alert(testnew)
The value that testnew shows in the alert is 25.
Get an amount out of a text
If you need to extract an amount out of a string you can use regex for that.
string.replace(/[^0-9\./]/g, '')
This extracts the decimals and the . from a string. Here is an example.
string = "the amount is 15,22"
alert(string.replace(/[^0-9\,/]/g, ''))
If you need to extract an amount out of a string you can use regex for that.
string.replace(/[^0-9\./]/g, '')
This extracts the decimals and the . from a string. Here is an example.
string = "the amount is 15,22"
alert(string.replace(/[^0-9\,/]/g, ''))
Get the first word of a string
To get the first word of a string you can use:
var string = "Javascript is the language"
var firstword = string.split(" ")[0]
alert(firstword)
To get the first word of a string you can use:
var string = "Javascript is the language"
var firstword = string.split(" ")[0]
alert(firstword)
Get the last word of a string
To get the last word in a string use the following snippet.
var month = "jan 30";
var temperature = month.substring(month.lastIndexOf(" "));
alert(temperature)
You can also use the snippet discussed in the trick where we split the first name and surname.
Get the last word in a string 2
Here is another way to get the last word in a string.
a = "This is a test with Javascript"
alert(a.split(" ").pop())
Get the last x letters out of a string
To get the last x letters out of a string you can use the next snippet:
string = "123456789"
result=str.slice(-4)
alert(result)
The command slice(-4) distills the last 4 letters out of the string.
If you need the third and fourth letter from the back you can change this in:
string = "123456789"
result=str.slice(-4, -2)
alert(result)
This takes the fourth letter from the back to the third letter. This results in the figures 6 and 7. Using (-4, -1) would result in "678".
To get the last x letters out of a string you can use the next snippet:
string = "123456789"
result=str.slice(-4)
alert(result)
The command slice(-4) distills the last 4 letters out of the string.
If you need the third and fourth letter from the back you can change this in:
string = "123456789"
result=str.slice(-4, -2)
alert(result)
This takes the fourth letter from the back to the third letter. This results in the figures 6 and 7. Using (-4, -1) would result in "678".
How many times does a letter occur in a string
For counting how many times a certain letter occurs in a string you can use the next snippet.
var string1 = "Javascript tips";
var letter = "s";
var aantal;
for (var i = aantal = 0; i < string1.length; aantal += (string1[i++] == letter));
alert(aantal);
This only works with single letters. If you want to test for letters and words use the tip described in: How many times does a string occur in another string
How many times does a letter occur in a string 2
Here are two other methods to count how many times a letter occurs in a string. Both methods count how many times the letter i appears. Here is the first method.
var teststring = "Javascript tips";
var number = teststring.split("i").length-1
alert(number);
And here is the next
var teststring = "Javascript tips";
var number = (teststring.match(/i/g) || []).length
alert(number);
How many times do a letter or word appear in a string
Here is an easy method that shows how many times a word or character appear in a string.
var temp = "Javascript tips";
alert(temp.split('ip').length-1);
The string is splitted on the searched word or letter. In this example it is splitted in "Javascr", "t t", and "s" so in 3 parts. This means that "ip" occurs twice.
Here is an easy method that shows how many times a word or character appear in a string.
var temp = "Javascript tips";
alert(temp.split('ip').length-1);
The string is splitted on the searched word or letter. In this example it is splitted in "Javascr", "t t", and "s" so in 3 parts. This means that "ip" occurs twice.
How many times do all letters or figures occur in a string.
The next5 snippet gives an object that presents a list of how many times each letter or figure occurs in a string.
const str = 'aabb3333bc1dd55d';
const mapString = str => {
const map = {};
for(let i = 0; i < str.length; i++){
map[str[i]] = (map[str[i]] || 0) + 1;
};
return map;
};
console.log(mapString(str));
The next5 snippet gives an object that presents a list of how many times each letter or figure occurs in a string.
const str = 'aabb3333bc1dd55d';
const mapString = str => {
const map = {};
for(let i = 0; i < str.length; i++){
map[str[i]] = (map[str[i]] || 0) + 1;
};
return map;
};
console.log(mapString(str));
How many times does a string occur in another string
Working with sensor readings we sometimes want to know how often a certain reading occurs. In the next example temperatures have been stored into a string. If we want to know how often a certain temperature occurs we can use the next script lines:
var temp = "33.3 35.2 20.36 33.3 26.4 28.5 33.3";
var search = "33.3";
var regex = new RegExp(search, "gi");
var quantity = (temp.match(regex) || []).length;
alert(quantity);
How to check if a string only contains all the same characters
If you need to check if a string contains all the same characters or a certain character you can check the length of that string, remove the character and test the length again. Here is an example.
let str = " ";
before = str.length
str2=str.replaceAll(" ","")
after = str2.length
alert(before>after)
If you need to check if a string contains all the same characters or a certain character you can check the length of that string, remove the character and test the length again. Here is an example.
let str = " ";
before = str.length
str2=str.replaceAll(" ","")
after = str2.length
alert(before>after)
Insert a variable into a string
To insert a variable into a string we normally use the following method.
var age = "36"
var string = "I am now " + age + " year old"
alert(string)
Javascript now has a function that is called string literals which do the same. You can use it as follows.
var age = "36";
var string = `I am now ${age} year old`;
alert(string)
To be able to use this you need to use backticks in the string definition.
To insert a variable into a string we normally use the following method.
var age = "36"
var string = "I am now " + age + " year old"
alert(string)
Javascript now has a function that is called string literals which do the same. You can use it as follows.
var age = "36";
var string = `I am now ${age} year old`;
alert(string)
To be able to use this you need to use backticks in the string definition.
Loop over a string
If you need to loop over a string you can do that as follows:
var text = 'Javascript';
for (var value of text)
{
console.log(value);
}
If you need to loop over a string you can do that as follows:
var text = 'Javascript';
for (var value of text)
{
console.log(value);
}
Make sure the first letter after a colon is a capital
It happens sometimes that we have a text which includes a colon. For example Name: luc Volders. This can happen when we make a string from some Object data. To make sure that the first letter after the colon is capitalised we can use the next function:
var data='name: luc Volders';
function capitalisefirst(name)
{
return name.replace(/([:\?]\s+)(.)/g, function(namecap)
{
return namecap.toUpperCase();
});
}
alert(capitalisefirst(data));
The regular expression captures the first letter after the colon and toUpperCase() converts that to a capitalised letter.
new String creates an object
Please beware that if you use new String to copy aor create a string the result is not a string but an object. Here is an example.
var original = "A normal string";
var newstring = new String(original);
alert(typeof(newstring))
Please beware that if you use new String to copy aor create a string the result is not a string but an object. Here is an example.
var original = "A normal string";
var newstring = new String(original);
alert(typeof(newstring))
Quotes in a string
Sometimes we need to put a quote in a string. As quotaion marks within quaotation marks are not directly allowed we can use backslash to achieve what we want:
var string1 = "He said \"Hey this works\"";
Remove all non numeric characters except the dot
The next line shows how to remove all non numeric characters out of a string except the figures and the decimal dot.
var string = "The temperature is 28.5 degrees C"
var temp = string.replace(/[^\d.-]/g, '');
alert(temp)
The next line shows how to remove all non numeric characters out of a string except the figures and the decimal dot.
var string = "The temperature is 28.5 degrees C"
var temp = string.replace(/[^\d.-]/g, '');
alert(temp)
Remove everything after a word or character
If you need to remove everything after a certain word or character in a string you can use the next snippet.
var test = "Javascript tips, Luc Volders";
remaining = test.substring(0, test.lastIndexOf(","));
alert (remaining)
If you need to remove everything after a certain word or character in a string you can use the next snippet.
var test = "Javascript tips, Luc Volders";
remaining = test.substring(0, test.lastIndexOf(","));
alert (remaining)
Remove everything except the letters from a string
The next snippet shows how to remove all characters from a string except the letters.
var badstring = "12KLj mhg56"
var okstring = badstring.replace(/[^a-z]/gi, '')
alert(okstring)
Only the letters are shown. If you need the spaces to, to make full sentences add space to the regex expression like this:
okstring = badstring.replace(/[^a-z\s]/gi, '')
The next snippet shows how to remove all characters from a string except the letters.
var badstring = "12KLj mhg56"
var okstring = badstring.replace(/[^a-z]/gi, '')
alert(okstring)
Only the letters are shown. If you need the spaces to, to make full sentences add space to the regex expression like this:
okstring = badstring.replace(/[^a-z\s]/gi, '')
Remove the first and last characters from a string
The next line of code shows how to remove the first and last letter from a string.
var string = "*Javascript tips*";
var result = string.substring(1, string.length-1);
console.log(result);
The next line of code shows how to remove the first and last letter from a string.
var string = "*Javascript tips*";
var result = string.substring(1, string.length-1);
console.log(result);
Remove the first x characters from a string
To remove the first x letters of a string you can use the
next snippet.
var amount = 6;
var teststring = "Luc's Javascrip tips";
var newstring = teststring.substring(amount, teststring.length - amount);
alert(newstring);
Removing non alphabetic chracters from a string
The next program will filter all non alphabetic characters (exept space) from a string. Whats left is pure text.
let test = "h3ell55o LUC"
let testnew = ""
for (let i=0; i<test.length; i++)
{
if ((test[i].toLowerCase() !== test[i].toUpperCase()) || test[i] == " ")
{
alert(test[i]);
testnew = testnew + test[i];
}
}
alert(testnew)
The for loop tests each character if it is, when converted to lowercase, equal to uppercase. If that is true it is rejected. If this is not true the character is added to the new string. In this example the text hello LUC will be shown in the alert.
Remove numbers from a string
To remove any numbers out of a string you can use the following code.
var mixedtext = "Javascript 456 tips";
text = mixedtext.replace(/[0-9]/g, '');
alert(text);
Remove spaces in front and after a string
When you want to remove spaces in fron and behind a string you can use the build-in trim() function. Unfortunately that function does not work in all browsers. To get the same functionality you can use the following.
teststring = " Javascript tips ";
alert(teststring + " : " + teststring.length)
test2 = teststring.replace(/^\s+|\s+$/gm,'');
alert(test2 + " : " + test2.length)
The first alert wil show the length being 27, The second alert shows the trimmed length being 15
Remove the first n words out of a string
To remove the first n words out of a string use the following example.
teststring = "A rather long sentence from Javascript tips";
var remove = 5;
teststring = teststring.split(" ").slice(remove).join(' ');
alert(teststring);
To remove the first n words out of a string use the following example.
teststring = "A rather long sentence from Javascript tips";
var remove = 5;
teststring = teststring.split(" ").slice(remove).join(' ');
alert(teststring);
Remove the last word from a string
To remove the last word from a string use the next snippet.
var teststring= "Remove the last word";
teststring = teststring.substring(0, teststring.lastIndexOf(" "));
Remove the last x letters from a string
To remove the last x letters of a string you can use the
next snippet.
var amount = 5;
var teststring = "Luc's Javascript tips";
var newstring = teststring.substring(0, teststring.length - amount);
alert(newstring);
To remove the last x letters of a string you can use the
next snippet.
var amount = 5;
var teststring = "Luc's Javascript tips";
var newstring = teststring.substring(0, teststring.length - amount);
alert(newstring);
Replace a string case insensitive
One of the previous tips showed how to change part of a string in
something else. That only functioned case dependend. The next
snippet shows how to replace a text case insensitive.
The regex expression gi searches global and case insensitive.
var teststring = "Javascript javascript"
var result = teststring.replace(/j/gi, "J");
alert (result)
One of the previous tips showed how to change part of a string in
something else. That only functioned case dependend. The next
snippet shows how to replace a text case insensitive.
The regex expression gi searches global and case insensitive.
var teststring = "Javascript javascript"
var result = teststring.replace(/j/gi, "J");
alert (result)
Replace all occurences in a string
To replace certain letters in a string we can use String.replace(). However that will only replace the first occurence in a string. If we want to replace all occurences you can use regex like shown here.
var teststring = "luc luc";
alert(teststring.replace("l", "L"));
This is the normal method and alert wil show "Luc luc" which is not what we want.
var teststring = "luc luc";
alert(teststring.replace(/l/g, "L"));
Now the alerts will show "Luc Luc" which is what we were trying to achieve. Just be carefull as this will replace all occurences of "l" in "L". If you do not want that to happen search for a more specific string like the next example.
var teststring = "luc letters level luc";
alert(teststring.replace(/lu/g, "Lu"));
To replace certain letters in a string we can use String.replace(). However that will only replace the first occurence in a string. If we want to replace all occurences you can use regex like shown here.
var teststring = "luc luc";
alert(teststring.replace("l", "L"));
This is the normal method and alert wil show "Luc luc" which is not what we want.
var teststring = "luc luc";
alert(teststring.replace(/l/g, "L"));
Now the alerts will show "Luc Luc" which is what we were trying to achieve. Just be carefull as this will replace all occurences of "l" in "L". If you do not want that to happen search for a more specific string like the next example.
var teststring = "luc letters level luc";
alert(teststring.replace(/lu/g, "Lu"));
Replace first letter of first word with capital
Not everyone enters text neatly. Sometimes people Ommit capitals as the first letter of a sentence. The next program corrects this.
let origtext = "hello. this is a test. the last line."
let hulptxt = "";
let hulpar = origtext.split(". ");
for (number in hulp)
{
hulptxt = hulpar[number][0].toUpperCase();
hulptxt = hulptxt + hulpar[number].slice(1,hulpar[number].length);
hulpar[number] = hulptxt;
}
origtext = hulpar.join(". ");
alert(origtext);
First the text is split into seperate lines in an array. Then the first character of each array entry is converted to uppercase. Then the rest of the sentence is added and the corrected text is stored back into the array. Lastly the array is converted to the original single variable in which we replace the array's , seperator with ". "
Not everyone enters text neatly. Sometimes people Ommit capitals as the first letter of a sentence. The next program corrects this.
let origtext = "hello. this is a test. the last line."
let hulptxt = "";
let hulpar = origtext.split(". ");
for (number in hulp)
{
hulptxt = hulpar[number][0].toUpperCase();
hulptxt = hulptxt + hulpar[number].slice(1,hulpar[number].length);
hulpar[number] = hulptxt;
}
origtext = hulpar.join(". ");
alert(origtext);
First the text is split into seperate lines in an array. Then the first character of each array entry is converted to uppercase. Then the rest of the sentence is added and the corrected text is stored back into the array. Lastly the array is converted to the original single variable in which we replace the array's , seperator with ". "
Replace spaces in _ and all letters in uppercase
If you want to replace all spaces in a string into _ (underscore) and at the same time want to convert all letters to upprcase you can use the next snippet.
var testline = "This is a test. Two lines";
var converted = testline.replace(/ /g,'_').toUpperCase();
console.log(converted);
If you want to replace all spaces in a string into _ (underscore) and at the same time want to convert all letters to upprcase you can use the next snippet.
var testline = "This is a test. Two lines";
var converted = testline.replace(/ /g,'_').toUpperCase();
console.log(converted);
Replace without regex
If you want to replace certain characters or words in a string but are not fluent in regex: no worries. Here is another method.
var teststring = "luc letters level luc";
teststring = teststring.replaceAll('lu','Lu')
alert(teststring)
ReplaceAll will replace all occurences of "lu" into "Lu"
Another option would be to use split() to split the string at the letters "lu" and then join them again with "Lu" like this:
string = string.split('lu').join('Lu')
You could even do this in a while loop:
var teststring = "luc letters level luc";
while (teststring.includes('lu'))
teststring = teststring.replace('lu', 'Lu')
alert(teststring)
If you want to replace certain characters or words in a string but are not fluent in regex: no worries. Here is another method.
var teststring = "luc letters level luc";
teststring = teststring.replaceAll('lu','Lu')
alert(teststring)
ReplaceAll will replace all occurences of "lu" into "Lu"
Another option would be to use split() to split the string at the letters "lu" and then join them again with "Lu" like this:
string = string.split('lu').join('Lu')
You could even do this in a while loop:
var teststring = "luc letters level luc";
while (teststring.includes('lu'))
teststring = teststring.replace('lu', 'Lu')
alert(teststring)
Reverse the letters in a string
Javascript has a build in function for reversing the elements in an array. There is no such function for reversing the letters in a string. Here is a function that achieves this.
var teststring;
var newstring;
function turnaround(teststring)
{
if((typeof teststring) !== "string")
{
return;
}
var numberletters = teststring.length;
newstring='';
while(numberletters > 0)
{
numberletters --;
newstring += teststring[numberletters];
}
return newstring;
}
alert("The reversed string is: " + turnaround("spiT tpircsavaJ"));
Javascript has a build in function for reversing the elements in an array. There is no such function for reversing the letters in a string. Here is a function that achieves this.
var teststring;
var newstring;
function turnaround(teststring)
{
if((typeof teststring) !== "string")
{
return;
}
var numberletters = teststring.length;
newstring='';
while(numberletters > 0)
{
numberletters --;
newstring += teststring[numberletters];
}
return newstring;
}
alert("The reversed string is: " + turnaround("spiT tpircsavaJ"));
Reverse the letters in a string 2
To reverse the letters in a string we can convert the string to an array, reverse the array elements and joint them aging to a string. The next snippet does that.
function turnaround(teststring)
{
return [...teststring].reverse().join('');
}
test = turnaround("spiT tpircsavaJ");
alert (test);
If you do not want to use the spread operator you can use split() instead:
return teststring.split("").reverse().join('');
To reverse the letters in a string we can convert the string to an array, reverse the array elements and joint them aging to a string. The next snippet does that.
function turnaround(teststring)
{
return [...teststring].reverse().join('');
}
test = turnaround("spiT tpircsavaJ");
alert (test);
If you do not want to use the spread operator you can use split() instead:
return teststring.split("").reverse().join('');
Reverse the letters in a string 3
WE can reverse the letters in a string by splitting the string in array elements, then reversing the elements and joining the elements back into a string. Here is an example.
function turnaround(string){
return string.split("").reverse().join("");
}
turned = (turnaround("olleh"))
alert(turned)
WE can reverse the letters in a string by splitting the string in array elements, then reversing the elements and joining the elements back into a string. Here is an example.
function turnaround(string){
return string.split("").reverse().join("");
}
turned = (turnaround("olleh"))
alert(turned)
Safely combine multiple variables into a string
When there are several variables which can be strings and numbers and they have to be combined to one variable use concat().
var first = 1;
var second = 2;
var third = 3;
var combined = "".concat(first, second, third);
This will make combined a string containing "123".
If you would use first + second + third then Javascript would add the values to 6.
When there are several variables which can be strings and numbers and they have to be combined to one variable use concat().
var first = 1;
var second = 2;
var third = 3;
var combined = "".concat(first, second, third);
This will make combined a string containing "123".
If you would use first + second + third then Javascript would add the values to 6.
Search a string on the x'th occurence
Take a look at the next string.
var string = "Basic C++ Javascript Basic Lua Basic Python Basic";
If you need to know at what position the 3d occurence of Basic is you can use the next snippet.
function where(string, subString, index)
{
return string.split(subString, index).join(subString).length;
}
console.log(where(string, 'Basic', 3))
You can change the number 3 for the 3d occurence in any other occurence number. If you pass a number that is out of range the length of the string will be displayed
Take a look at the next string.
var string = "Basic C++ Javascript Basic Lua Basic Python Basic";
If you need to know at what position the 3d occurence of Basic is you can use the next snippet.
function where(string, subString, index)
{
return string.split(subString, index).join(subString).length;
}
console.log(where(string, 'Basic', 3))
You can change the number 3 for the 3d occurence in any other occurence number. If you pass a number that is out of range the length of the string will be displayed
Shortening a string
If you need to show several words that all have the same length you have to shorten them to that length. You can use substr(0,x) for that in which 0 is the starting character and x the ending character.
var line = "================================================";
alert(line.substr(0,9);
This makes it also easy to create lines of different lengths without each time having to manually fill in the "="
If you need to show several words that all have the same length you have to shorten them to that length. You can use substr(0,x) for that in which 0 is the starting character and x the ending character.
var line = "================================================";
alert(line.substr(0,9);
This makes it also easy to create lines of different lengths without each time having to manually fill in the "="
Sort a strings letters
When needed you can sort the letters in a string with the following line of code:
alert ("Javascript tips".split("").sort().join(""));
When needed you can sort the letters in a string with the following line of code:
alert ("Javascript tips".split("").sort().join(""));
Sort the words in a string on length
To sort the words in a string according to length you can use the following snippet.
var text = 'Python Javascript C++';
function sortonlength()
{
var textarray = text.split(' ');
var sorted = textarray.sort(function(a, b)
{
return a.length - b.length;
})
return sorted.join(' ');
};
alert(sortonlength(text));
By making a small adjustment you can use this also to sort an array on length.
To sort the words in a string according to length you can use the following snippet.
var text = 'Python Javascript C++';
function sortonlength()
{
var textarray = text.split(' ');
var sorted = textarray.sort(function(a, b)
{
return a.length - b.length;
})
return sorted.join(' ');
};
alert(sortonlength(text));
By making a small adjustment you can use this also to sort an array on length.
Split first name and surname
To split a name into a first name and surname you can use the next snippet.
var name = "Luc Volders";
var firstname;
var surname;
[firstname, surname] = name.split(" ");
alert(firstname);
alert(surname);
In this case we use destructuring to split the name with one command.
Another method would be to use split() and splice()
var firstName = name.split(' ').slice(0, -1).join(' ');
var lastName = name.split(' ').slice(-1).join(' ');
To split a name into a first name and surname you can use the next snippet.
var name = "Luc Volders";
var firstname;
var surname;
[firstname, surname] = name.split(" ");
alert(firstname);
alert(surname);
In this case we use destructuring to split the name with one command.
Another method would be to use split() and splice()
var firstName = name.split(' ').slice(0, -1).join(' ');
var lastName = name.split(' ').slice(-1).join(' ');
Split a tekst in multiple lines
For convenience you can split a string in multiple lines.
testext = "This is \
a text \
of multiple \
lines";
alert(testext);
document.write(testext);
The \ will not be part of the tekst.
For convenience you can split a string in multiple lines.
testext = "This is \
a text \
of multiple \
lines";
alert(testext);
document.write(testext);
The \ will not be part of the tekst.
Strange addition
Javascript has some strange features. Just try the next snippet.
alert(("b" + "a" + + "a" + "a").toLowerCase())
Javascript has some strange features. Just try the next snippet.
alert(("b" + "a" + + "a" + "a").toLowerCase())
Subtract a number from a string yields the answer as a string
We all know that if you use + to combine strings with numbers the string is concatenated in stead of the numbers being added.
"" + 10 + 5 + 21
This will build this string : "10521"
2023 + "5" will build this string : "2028"
However subtracting yield a totally different result. Subtracting a number from a string will yield the answer as a string.
2023 - "8" will yield "2015" just like
"2023" - 8 will also yield "2015"
We all know that if you use + to combine strings with numbers the string is concatenated in stead of the numbers being added.
"" + 10 + 5 + 21
This will build this string : "10521"
2023 + "5" will build this string : "2028"
However subtracting yield a totally different result. Subtracting a number from a string will yield the answer as a string.
2023 - "8" will yield "2015" just like
"2023" - 8 will also yield "2015"
Test if a character is a letter or a sign
We can test individual characters in a string on if they are a letter or a sign. If we convert signs to capitals they remail the same.
character = "!";
alert(character.toUpperCase() !== character.toLowerCase())
Signs will give true as value and so will figures. Their uppercase and lowercase are the same. Letters like a-z wil change into A_Z and therefore will give false.
We can test individual characters in a string on if they are a letter or a sign. If we convert signs to capitals they remail the same.
character = "!";
alert(character.toUpperCase() !== character.toLowerCase())
Signs will give true as value and so will figures. Their uppercase and lowercase are the same. Letters like a-z wil change into A_Z and therefore will give false.
Test if a character or word is present in a string
Here is a quick test to check wether a character or word is present in a string.
var text = "this is a test"
if (text.indexOf("is") >-1)
{
console.log("the searched word is present")
}
indexOf(0 gives the place where the searched word is in the string. So if it's value is 0 or larger it is present. Beware that in the searched string must be an exact match. Here "is" is two times found in "this" and "is".
Here is a quick test to check wether a character or word is present in a string.
var text = "this is a test"
if (text.indexOf("is") >-1)
{
console.log("the searched word is present")
}
indexOf(0 gives the place where the searched word is in the string. So if it's value is 0 or larger it is present. Beware that in the searched string must be an exact match. Here "is" is two times found in "this" and "is".
Test if a character or word is present in a string 2
Using text.startsWith ables us to test wether a character or word is at the beginning of a string.
var string = "Hello world"
alert(string.startsWith("Hello")
The alert will display "true"
We can add a second parameter to have the search starting further on in the string like this:
var string = "Hello world"
search = string.startsWith("world",5)
alert (search)
Now the alert will display "false"as the word world is at the sixth position. Counting starts here at 0.
Using text.startsWith ables us to test wether a character or word is at the beginning of a string.
var string = "Hello world"
alert(string.startsWith("Hello")
The alert will display "true"
We can add a second parameter to have the search starting further on in the string like this:
var string = "Hello world"
search = string.startsWith("world",5)
alert (search)
Now the alert will display "false"as the word world is at the sixth position. Counting starts here at 0.
Test if a string is an anagram
The next snippet shows how to test if a string is an anagram of another string.
function testanagram(string1, string2)
{
string1test = string1.toLowerCase().split('').sort().join('');
string2test = string2.toLowerCase().split('').sort().join('');
return string1test == string2test;
}
alert(testanagram('listen', 'silent'));
alert(testanagram('loop', 'polo'));
alert(testanagram('this', 'shit'));
The next snippet shows how to test if a string is an anagram of another string.
function testanagram(string1, string2)
{
string1test = string1.toLowerCase().split('').sort().join('');
string2test = string2.toLowerCase().split('').sort().join('');
return string1test == string2test;
}
alert(testanagram('listen', 'silent'));
alert(testanagram('loop', 'polo'));
alert(testanagram('this', 'shit'));
Test if a string is a palindrome
A palindrome is a word that backwards is the same word. Examples are civic, racecar, madam. The next lines show how to test if a word or sentence is a palindrome.
var string = "racecar";
var strReverse = string.split("").reverse().join("");
if (string === strReverse) {
alert("This is a palindrome");
} else {
alert("No, this is not a palindrome");
A palindrome is a word that backwards is the same word. Examples are civic, racecar, madam. The next lines show how to test if a word or sentence is a palindrome.
var string = "racecar";
var strReverse = string.split("").reverse().join("");
if (string === strReverse) {
alert("This is a palindrome");
} else {
alert("No, this is not a palindrome");
Test if a string contains numbers
If you need to know wether there are numbers in a string you can use the next snippet.
teststring = "Temperature is 23 degrees"
result =/\d/.test(teststring)
alert(result)
If you need to know wether there are numbers in a string you can use the next snippet.
teststring = "Temperature is 23 degrees"
result =/\d/.test(teststring)
alert(result)
Test if a text is present in another text
If you need to know if a text occurs in another text you can use the following snippet:
var string = "Hello"
var searchstring = "llo"
console.log(string.includes(searchstring))
If you need to know if a text occurs in another text you can use the following snippet:
var string = "Hello"
var searchstring = "llo"
console.log(string.includes(searchstring))
Test wether two strings are case insensitive equal
In a program you might get an input from a user that is what you are looking for but user uses only lower case or mixed upper and lower case while your text is the same kust the lower/upper case setting is different. here is how you can check that.
var text1 = 'An example';
var text2 = 'an Example';
text1 = text1.toLowerCase();
text2 = text2.toLowerCase();
equaltest = (text1 === text2);
console.log(equaltest);
Here the log will show true.
In a program you might get an input from a user that is what you are looking for but user uses only lower case or mixed upper and lower case while your text is the same kust the lower/upper case setting is different. here is how you can check that.
var text1 = 'An example';
var text2 = 'an Example';
text1 = text1.toLowerCase();
text2 = text2.toLowerCase();
equaltest = (text1 === text2);
console.log(equaltest);
Here the log will show true.
Use padStart to add predecesser characters
Using padStart we can add characters (numbers or strings) at the beginning of a string. We need to supply the number of characters and which characters to use. Here are a few examples to clarify.
var test = "6";
var test2 = "25";
alert (test.padstart(4,0));
alert (test2.padstart(2,0));
The first alert shows 0006 because we indicate that the result should become 4 characters and that the leading characters should be 0.
The second alert will show 25 because we indicated that the result should be a string of maximum of 2 characters which it already is.
var minute = 3
alert (minute.toString().padStart(2,0));
In this example the number 3 is converted to a string and padStart puts a 0 in front of it.
var minute = 3
alert (minute.toString().padStart(20,"-*"));
We can put multiple characters behind the comma. In this example the number 3 is converted to a string and multiple -* are put in fron till a total of 20 characters is reached.
Using padStart we can add characters (numbers or strings) at the beginning of a string. We need to supply the number of characters and which characters to use. Here are a few examples to clarify.
var test = "6";
var test2 = "25";
alert (test.padstart(4,0));
alert (test2.padstart(2,0));
The first alert shows 0006 because we indicate that the result should become 4 characters and that the leading characters should be 0.
The second alert will show 25 because we indicated that the result should be a string of maximum of 2 characters which it already is.
var minute = 3
alert (minute.toString().padStart(2,0));
In this example the number 3 is converted to a string and padStart puts a 0 in front of it.
var minute = 3
alert (minute.toString().padStart(20,"-*"));
We can put multiple characters behind the comma. In this example the number 3 is converted to a string and multiple -* are put in fron till a total of 20 characters is reached.
Which letter corresponds with a number
Our alphabet consists of the letters a-z and we have the capital A-Z. So 26 letters and 26 capitals. If we have a number and want to know its corresponding letter we canb use the next code.
function letter(number)
{
if(number < 1 || number > 26 || typeof number !== 'number')
{
return -1;
}
var start = 96;
return String.fromCharCode(number + start);
};
alert(letter(26));
Here the numbers from 1 to 26 correspond with the letters a-z. If you change var start = 96; in var start = 64; you will get the corresponding capiatls.
Our alphabet consists of the letters a-z and we have the capital A-Z. So 26 letters and 26 capitals. If we have a number and want to know its corresponding letter we canb use the next code.
function letter(number)
{
if(number < 1 || number > 26 || typeof number !== 'number')
{
return -1;
}
var start = 96;
return String.fromCharCode(number + start);
};
alert(letter(26));
Here the numbers from 1 to 26 correspond with the letters a-z. If you change var start = 96; in var start = 64; you will get the corresponding capiatls.
Wich place has a letter in the alphabet
This tip reverses the tip "Which letter corresponds with a number". We have a letter and want to know where its place in the alphabet is. We can find that as follows.
letter = "A"
const ascii = tekst.charCodeAt(0);
alert(ascii)
If the letters is a capaital the alert will give a value from 65 (A) to 90 (Z) otherwise the valuw will be from 97 (a) to 122 (z).
This tip reverses the tip "Which letter corresponds with a number". We have a letter and want to know where its place in the alphabet is. We can find that as follows.
letter = "A"
const ascii = tekst.charCodeAt(0);
alert(ascii)
If the letters is a capaital the alert will give a value from 65 (A) to 90 (Z) otherwise the valuw will be from 97 (a) to 122 (z).