-3

I am looking for the correct syntax to remove all characters which immediately follow on from the final capital letter in a string. For example, 'FirstName' becomes 'FirstN'.

Can anyone help me with the JavaScript code?

dreamviewer
  • 145
  • 2
  • 7

3 Answers3

1

Loop from the end to the beginning until you find a uppercase letter, then do a substring to keep only the part before. Here is an exemple on how to find if a letter is upper or not:

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

Community
  • 1
  • 1
Shryme
  • 1,572
  • 1
  • 14
  • 22
1
function shorten(str) {
    return str.slice(0, (function() {
        for (var i=str.length; i--;) {
            if (str.charAt(i).match(/[A-Z]/)) return ++i;
        }
    })())
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Why do you split a string when you can already do str[i]? – Shryme Dec 02 '13 at 17:57
  • @Shryme - To `pop()` it ! – adeneo Dec 02 '13 at 17:58
  • 1
    Converting string to Array isn't necessary. Popping off one at a time isn't necessary. And you're assuming all characters will be letters or spaces. If you're going to answer easy questions like this for people who have clearly not tried anything, at least give it a better effort. – Blue Skies Dec 02 '13 at 17:59
  • If it makes you happy, I can do it whithout the array, and search for specific uppercase letters within the A-Z range instead. – adeneo Dec 02 '13 at 18:05
  • @BlueSkies - better ? – adeneo Dec 02 '13 at 18:10
  • No explanation? Because the OP doesn't show any effort? – Felix Kling Dec 02 '13 at 18:12
  • @FelixKling - Yup, it's just a function using three methods and a loop, so googling those three methods should give the OP something to do ? – adeneo Dec 02 '13 at 18:18
0

You can use regex...

var text = "FirstName";
var newText = text.replace(/([A-Z])[a-z]*$/,"$1");

Live JSFiddle Demo

freefaller
  • 19,368
  • 7
  • 57
  • 87
  • Thanks to everyone who helped. I had tried various different methods, but none even came close so I did not paste it into my question. @freefaller, this works perfectly! Much appreciated! – dreamviewer Dec 03 '13 at 15:48
  • You're welcome @dreamviewer, good luck with the rest of your project – freefaller Dec 03 '13 at 15:50