that one kid
that one kid

Reputation: 11

how can I remove a variable amount of characters from the end of javascript string

I've been trying to get something like this to work but it just won't:

var str = str.slice(0, -"variable");

I need to remove a variable amount of characters from the end. thanks!

Upvotes: 1

Views: 74

Answers (2)

Ele
Ele

Reputation: 33726

This -"variable" is a coercion logic, so basically you're executing something as follow: str.slice(0, NaN);

console.log(-"variable"); // js engine is trying to convert to number

Just use the variable, you don't need to wrap it with quotes like a string.

var variable = 5;
var str = "EleFromStack".slice(0, -variable);
console.log(str)

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44107

Use slice:

var str = "Hello, World";
var chars = 7;
var sliced = str.slice(0, -chars);
console.log(sliced);

Upvotes: 3

Related Questions