+ 5

How to delete a letter from a string??

We have a code: var inp=String(prompt()) var a=inp.indexOf("p") delete inp[a] a; Idk why but it outputs the same string but we deleted "p". Are there any ways to delete a letter from a string?

6th Apr 2018, 6:30 PM
4 Answers
+ 6
You can use "delete" to remove a key from associative array or object. substr() var a = inp.indexOf("p") inp = inp.substr(0, a) + inp.substr(a + 1, inp.length); slice() var a = inp.indexOf("p"); inp = inp.slice(0, a) + inp.slice(a + 1, inp.length); You can rebuild the string and miss the letter "p". var a = inp.indexOf("p"); var re = ""; for(var k = 0; k < inp.length; k++) { if(a != k) re += inp[k]; } There's a lot of ways. Depends what you want to use
6th Apr 2018, 6:34 PM
Toni Isotalo
Toni Isotalo - avatar
+ 23
//if u know which one letter to be deleted...: //add this 1 also var inp = prompt(); var res = inp.replace(/p/g,""); document.write(res); //g = case sensitive p //gi = case-insensitive p check this link 👇 https://www.w3schools.com/jsref/jsref_replace.asp
6th Apr 2018, 6:54 PM
🌛DT🌜 - avatar
+ 5
Thanks guys!
7th Apr 2018, 10:44 AM
+ 3
Hi Talentless_guy It is a rookie mistake to confuse strings and arrays in JavaScript. Strings are immutable ie they cant be changed. Arrays are mutable so you can change them. They also have different methods. So while you can reference a character in a string using array bracket notation ie mystring[2] , you cant assign a new character to it like this mystring[2]='x'. that is because there is no char type in JS, s in this case is another string. You have to convert the string to an array using string.split method, change the letter you want and convert back to a new string using string.join method: let testString="Hello How Are You"; let stringArr=testString.split(""); stringArr[2]='x'; let newString = stringArr.join(""); console.log(newString); //Hexlo How Are You There are less verbose ways of doing this (eg string.replace), but above will help you understand strings vs arrays.
7th Apr 2018, 9:50 AM
Mike Choy
Mike Choy - avatar