You are currently viewing How to Remove First Character from String Javascript

How to Remove First Character from String Javascript

Three ways to Remove first character from string javascript

In this article, we’ll see how to remove the first character from a string in JavaScript. We will remove the character in the string using the replace method, slice method, and substring or substr method.

1. Replace():

let st="Hello World";
st=st.replace("H","");
console.log(st);

/*
Output : ello World
*/

 

let st="Helllo World";
st=st.replace(/l/g,"");
console.log(st);

/*
Output : Heo World
*/

2. slice():

//Removing character from particluar position
//slice(starting,ending+1) = 0 to length-1
let str="Welcome";
str=str.slice(1,str.length);
console.log(str);

/*
output : elcome
*/

3. substring() or substr()

let str="JavaScript";
str=str.substring(1,str.length);
console.log(str);

/*
output : avaScript
*/
let str="JavaScript";
str=str.substr(1);
console.log(str);

/*
output : avaScript 
*/

Remove character using the function:

function removeChar(str, pos){
str = str.slice(0,pos) + str.slice(pos+1, str.length);
return str;
}

console.log(removeChar("Hello@ there", 5));

/*
Output : Hello there
*/

In the above code, we have a function called “removeChar” with passing parameters string as well as the position. Here str stands for the string and pos stands for the position of the character you want to be removed. Then inside the function, we have a standard formula using substring or slice. We will take the position value and create substrings from zero position to pos. Then return the str.

And the last line, we call the function removeChar and passed the string ‘Hello@ there’ and position ‘5’. So, in the 5th position character ‘@’ is removed from the string.

Leave a Reply