0

I have a function which gives random Playernames which are sometimes longer than 14 letters. If that happens i want to delete the last characters so its 14 letters long and add "..." to it

Thats what I got so far. I tried substring too but it didnt work as well. Thanks for helping

var playername;
function delString(){
    if (playername.length >= 14){
        var rest = playername.length - 14;
        playername.slice(0, playername.length -rest);
        playername = playername + "...";
    }
}
Nicht Eric
  • 29
  • 5
  • Why don't you just code a function that gives out a 14-character random username ? – Yassine Badache Nov 09 '17 at 16:19
  • 1
    Hint why replace "didn't work" for you, **string is *immutable*** – Trash Can Nov 09 '17 at 16:19
  • See the linked question's answers, substituting `substring` or `slice` for `replace`. – T.J. Crowder Nov 09 '17 at 16:20
  • I dont know when i use slice it copies the part after the 14. character and pastes it behind the string and substring just doesnt do anything – Nicht Eric Nov 09 '17 at 16:22
  • 2
    Operations on strings create new strings. You need to capture the returned string from the operation and work with that. `var newString = playername.slice(0, playername.length -rest);` – Scott Marcus Nov 09 '17 at 16:22
  • See working code here: https://repl.it/OBz4/1 – mhodges Nov 09 '17 at 16:24
  • @NichtEric: *"I dont know when i use slice it copies the part after the 14. character and pastes it behind the string"* Not in the code above it doesn't. *"...and substring just doesnt do anything..."* Again: See the linked question. Both `slice` and `substring` *return* a new string with the change, they don't change the one you call it on. – T.J. Crowder Nov 09 '17 at 16:27
  • Ok thank you all i got it now :) – Nicht Eric Nov 09 '17 at 16:30

1 Answers1

0

I tried substring too but it didnt work as well

No it works, when you use substring() it will return a new string and doesn't affect the original one, so you need to assign this result in your old string.

This is how it should be implemented:

function delString(name){
    if (name.length >= 14){
        name = name.substring(0, 13);
        name += "...";
    }
    return name;
}

Demo:

var playername = "I am longer than 14 chars";
function delString(name){
    if (name.length >= 14){
        name = name.substring(0, 13);
        name += "...";
    }
    return name;
}

console.log(delString(playername));
cнŝdk
  • 31,391
  • 7
  • 56
  • 78