4 Effective Ways to Remove Character from String using JavaScript
Looking to remove the character from string in JavaScript? Let’s discuss remove method details in this post.
Using substring() method
JavaScript substring() method retrieves the characters between two indexes and returns a new substring.
Two indexes are nothing but startindex and endindex.
Let’s try to remove the first character from the string using the substring method in the below example.
function removeFirstCharacter() {
var str = 'tracedynamics';
str = str.substring(1);
console.log(str);
}
Output:
racedynamics
Now let’s remove the last character from the string using the substring method in the below example.
function removeLastCharacter() {
var str = 'tracedynamics';
str = str.substring(0,str.length-1);
console.log(str);
}
Output:
tracedynamic
the length property is used to determine the last element position.
As per the output above, you can see that specified first and last characters are removed from the original string.
With substr() method
substr() method will retrieve a part of the string for the given specified index for start and end position.
Let’s remove the first character from string using substr function in the below example.
function removeFirstCharacter() {
var str = 'tracedynamics';
str = str.substr(1);
console.log(str);
}
Output:
racedynamics
Now let’s see how to remove the last character from string using substr function in the below example.
function removeLastCharacter() {
var str = 'tracedynamics';
str = str.substr(0,str.length-1);
console.log(str);
}
Output:
tracedynamic
using below JavaScript code, we can also remove whitespace character from a string.
function removeWhiteSpaceCharacter() {
var str = 'tracedynamics ';
str = str.substr(0,str.length-1);
console.log(str);
}
Output:
tracedynamics
As you can see from the above function, in the input string value there is whitespace at the end of the string which is successfully removed in the final output.
Using slice() method
slice() method retrieves the text from a string and delivers a new string.
Let’s see how to remove the first character from the string using the slice method.
function removeFirstCharacter() {
var str = 'tracedynamics';
str = str.slice(1);
console.log(str);
}
Output:
racedynamics
Now let’s remove the last character from string using the slice method.
function removeLastCharacter() {
var str = 'tracedynamics';
str = str.slice(0,str.length-1);
console.log(str);
}
Output:
tracedynamic
Using replace() method
Remove string javascript
replace() method is used to replace a specified character with the desired character.
This method accepts two arguments or parameters.
The first argument is the current character to be replaced and the second argument is the new character which is to be replaced on.
Let’s see how to replace the first character in a string using the replace function.
function replaceFirstCharacter() {
var str = 'tracedynamics';
str = str.replace('t','T');
console.log(str);
}
Output:
Tracedynamics
Now let’s replace the last character in JavaScript string using replace function.
function replaceLastCharacter() {
var str = 'tracedynamics';
str = str.replace('s','S');
console.log(str);
}
Output:
tracedynamicS
Now let’s replace specified character in a string using the replace method.
function replaceCharacter() {
var str = 'tracedynamics';
str = str.replace('d','D');
console.log(str);
}
Output:
traceDynamics
Also we can apply regular expression(regex)in the replace method to replace any complex character or special character in the string.
Regular expressions(regex) are also useful when dealing with a line break, trailing whitespace, or any complex scenarios.
Using above JavaScript methods, we can also remove characters on string array, line break, trailing whitespace, empty string, Unicode character, double quotes, extra spaces, char, parenthesis, backslash
We can remove multiple characters by giving the specified index for start and end position.
To conclude this tutorial, we covered various types of implementation to remove a character from string using JavaScript.
JavaScript substring() method retrieves the characters between two indexes and returns a new substring. substring method doesn’t replace the original string.
What is Javascript substring method?
JavaScript substring() method retrieves the characters between two indexes and returns a new sub string.
General syntax of substring method
string.substring(start, end)
start : Its the starting position where to start the retrieval, first character is at index 0. This parameter is mandatory. end : Its the position till end of extraction (i,e position up to, but not including). It’s an optional parameter.
Note: JavaScript substring() method doesn’t switch/replace the original string.
Following are some of the substring Examples.
Extracting from specific position from the string
var mystr = "Hello Substring!";
var result = mystr.substring(5);
console.log(result);
Result/Output
Substring!
To extract the first character from the String
var mystr = "Welcome Substring!";
var result = mystr.substring(0, 1);
console.log(result);
Result/Output
W
To extract the last character from the String
var mystr = "Welcome Substring";
var result = mystr.substring(16, 17);
console.log(result);
Result/Output
g
substring considers starting index and ending index. whereas, substr considers starting index and length of characters. Also the starting index (first argument) of substr method can be a negative integer.
Extract substring using regular expression(regex) pattern
Following example illustrates extracting a substring using regular expression.
var mystr = "abcdefsd22j";
var result = mystr.match(/a(.*)j/);
console.log(result[1]);
Result/Output
bcdefsd22
slice method Vs substring method?
Both functions are pretty similar in their syntax, but different in some aspects. Let’s go through the differences.
Common for both methods:
If start argument equals stop argument, then method returns an empty string. If stop argument is omitted, then method extracts the characters to the end of the string. If either of the argument is greater than the string’s length, then the string’s length will be considered instead.
Distinctions of substring() method:
If start > stop, then the substring method will swap the respective 2 arguments. If either of the argument is negative or is NaN, then it is considered as if it were 0.
Distinctions of slice() method:
If start > stop, then the slice method will return an empty string(“”). If start is negative then thn the method sets char from the end of string.
Separator and Limit are two arguments that a split method can accept.
Separator: It’s an optional argument. It defines the character or regular expression. If you don’t provide the separator character, it will return full string as an array.
Limit: It’s an optional argument. It defines how many times to split a matched value. If the limit is not specified, it will split at all matched values and return an array.
Note:
In separator for an empty string (“”) declaration, the string splits between each character.
In addition, there is a number of ways to split a string.
So we are trying to cover different string methods implementation below.
Also, note that the String replace method is different from the split method.
Replace method can be leveraged when you want to replace a specific string.
Split String Method Variations in JavaScript
Leveraging Split() method, we tried to cover numerous examples with JavaScript implementation.
Here you go.
split string by whitespace
Here is the JavaScript code to split string by whitespace.
var str = "Welcome To My Blog";
var re = str.split(" ");
console.log(re);
Result/Output
["Welcome", "To", "My", "Blog"];
By separator character and limit
Let’s create a script to split using separator and limit.
var str2 = "example two of character class";
var re = str2.split(" ", 1);
console.log(re);
Result/Output
["example"]
JS string split by comma(CSV)
The following examples illustrate “How to create a split comma separated string using JavaScript”.
Refer to the string input parameter and output field.
var myString = 'this,is,an,csv file';
var mySplits = myString.split(",");
console.log(mySplits);
Result/Output
[ "this", "is", "an", "csv file" ]
By slash using regular expression(regex) pattern
we can split string by slash by applying regular expression patterns. Refer to the below script for the string input parameter and output field.
var myString = 'this/is/slash';
var mySplits = myString.split(/[\\\/]/);
console.log(mySplits);
Result/Output
[ "this", "is", "slash" ]
Similarly vice versa in case you want to split using the backslash.
Following JavaScript split function example illustrates “how to split the string at index”.
function splitIndex(value, index) {
return value.substring(0, index) + "," +value.substring(index);
}
var result = splitIndex("3362174", 3);
console.log(result);
Result/Output
[336,2174]
Using regex(regular expression) pattern
We can str split by providing a regular expression pattern.
var date = "04-29-2017";
var mySplits = date.split(/[.,\/ -]/);
console.log(mySplits);
Result/Output
[ "04", "29", "2017" ]
By delimiters
var delimiter = "abcd+wxyz-ghi";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)',
'\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var result =
delimiter.split(new RegExp(separators.join('|'), 'g'));
console.log(result);
Result/Output
[ "abcd", "wxyz", "ghi" ]
With uppercase
var myString = 'HelloLetsSplitCharacterClass';
var mySplits = myString.split(/(?=[A-Z])/);
console.log(mySplits);
Result/Output
[ "Hello", "Lets", "Split", "Character", "Class" ]
Using the length method
var myString = "prototype,str,split,method";
var mySplits = myString.split(',').length;
console.log(mySplits);
Result/Output
4
To get the first element
var myString = "welcome_to_split function";
var mySplits = myString.split(/_(.+)/)[0];
console.log(mySplits);
Result/Output
welcome
The result/output seen using the JavaScript console log method or document write method.
Into array
In general, we create an array in our programming based on business logic.
So here split() function convert a single string into an array of strings.
var arrayString = "Regular Expression";
var myArraySplits = arrayString.trim().split(" ");
console.log(myArraySplits);
Result/Output
[Regular,Expression]
If you are looking to parse JSON string into an array, the following example illustrates that.
Also for multiple strings, we can loop through the values with the split method.
var fullData ='{"fname":"Thomas","lname":"Cook","city":"Miami",
"state":"Florida", "Hobbies":"golf,trading,chess,fishing"}';
var data = JSON.parse(fullData);
var getHobbies = data.Hobbies;
var getHobbiesArray = getHobbies.split(",");
console.log(getHobbiesArray);
Result/Output
[golf,trading,chess,fishing]
Using the split function, we can parse the query string as well.
Into chunks
var myString = '0204161980';
var myChunkSplits = myString.match(/.{1,2}/g);
console.log(myChunkSplits);
Result/Output
["02", "04", "16", "19", "80"]
Convert string to a character array using the split js string method
Receiving error JavaScript split is not a function?
You might be experiencing error “TypeError: string.split is not a function”.
This happens whenever you are calling .split() method on other than a string.
The JS runtime won’t find the .split() method for that data type. for such scenarios, you must ensure to pass a string to your function.
Here is an example:
var test = Hello Javascript;
result = test.split(" ");
console.log(result);
The above JavaScript snippet throws an error “TypeError: string.split is not a function”.
Since here we are trying to split the variable test ( Hello Javascript) which is not a string type.
The correct declaration of this split function should be as follows
var test = "Hello Javascript";
result = test.split(" ");
console.log(result);
So here we declared a variable test as a string (added string quotes “” to Hello JavaScript).
The result will be [Hello,JavaScript]
On newline
The following example will return an array of strings upon using the js split() method on the newline.
var arraytest = "cat\nrat";
result = arraytest.split("\n");
console.log(result);
Result/Output
["cat", "rat"]
split string to map method(using ES6 standard)
const string = "country:Finland, city:Helsiniki,";
const strvalue = string.split(",").map(pair=>pair.split(":"));
const result = new Map(strvalue);
console.log(result.get("country") );
Note: const is available in ES6 standard.
Result/Output
["Finland"]
Using reverse string
var result = 'reversestring'.split('').reverse().join('') ;
console.log(result);
Result/Output
["gnirtsesrever"]
var text = "I would \"like\" to \"split string\".";
var result = text.split("\"");
console.log(result);
Result/Output
[I would ,like, to ,split a string,.]
On special character
var text = "[email protected]_special.character";
var result = text.split(/[.\@_]/);
console.log(result);
Result/Output
[i,like,special,character]