Remove only the last space in a text | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Remove only the last space in a text

I would wish to get a simple code that only removes the last space in some text. It could be one word or a sentence, but there should be no space at the end. This is necessitated by the fact that when users are keying in names or other texts like security questions, they tend to press space subconsciously or even when they use the auto suggestions from most browsers and keyboards, I am still learning how to code, am yet to reach to this point of sophisticated coding. Your help would be great

12th Oct 2019, 4:30 AM
The Don
The Don - avatar
8 Answers
+ 4
I made a function for this task, using built-in method of the string class. See if it serves the requirements. function removeLastSpace(s) { if (!s.length) return ""; var pos = s.length - 1; while(s.charAt(pos) == " ") pos--; return s.slice (0, pos + 1); } console.log(removeLastSpace("Hello world! this is me! ")); Reference: https://www.w3schools.com/jsref/jsref_lastindexof.asp https://www.w3schools.com/jsref/jsref_slice_string.asp (Edited - 2) Thanks to Russ for noting the flaws, and for an idea using loop 👍
12th Oct 2019, 5:52 AM
Ipang
+ 2
use trim() in Java (Removes space from beginning as well as end)
12th Oct 2019, 7:06 AM
Infinity
Infinity - avatar
+ 2
Use Regex? let text = " hi " text = text.replace(/\s+$/, "") alert("_" + text + "_") //_ hi_ Or, if regex isn't your thing: let text = " hi " while (text[text.length - 1] == " ") { text = text.slice(0, text.length - 1) } alert("_" + text + "_") //_ hi_
12th Oct 2019, 8:39 AM
Russ
Russ - avatar
+ 2
Ipang I think your solution would work fine if only the original post didn't mention that text could be a sentence. If the user entered a sentence without the extra space at the end, I think your code would remove the last space and then the last word too.
12th Oct 2019, 8:46 AM
Russ
Russ - avatar
+ 2
Russ Thanks for pointing the case out, I was only testing with text having a space at their tails. I have edited my response and added a check there, but I gotta strong feeling someone will come up with a better solution in regex anytime soon 😁 (Edit) Oops you already have a regex solution, didn't see it earlier 😁
12th Oct 2019, 9:23 AM
Ipang
+ 1
The trim() function is what you're looking for. It's well supported, so there's no reason to not use it.
12th Oct 2019, 9:44 AM
DooM
+ 1
deleteCharAt(<strVar>.length()-1) also Trim() can be used.
12th Oct 2019, 10:55 AM
Hardik Prajapati
Hardik Prajapati - avatar
0
you can use trim()
16th Oct 2019, 4:29 AM
Shaili Shah
Shaili Shah - avatar