Modelesq
Modelesq

Reputation: 5382

Remove remaining string after / character javascript

I've been working with strings lately and I'm wondering how to go about solving how to remove remaining string after first / character.

this/is/my/string

Expected output:

This

My code:

string = string.slice(0, string.indexOf('/'));
result = string.charAt(0).toUpperCase() + string.slice(1);

What I'm getting is Thi... What am I doing wrong here? Remove after first / and capitalize doesn't seem to work as expected.

Upvotes: 0

Views: 225

Answers (2)

Jonathan.Brink
Jonathan.Brink

Reputation: 25373

The code you already have above actually worked for me. See: http://jsbin.com/vozecenufi/1/edit?js,console

But, this approach may be cleaner:

var s = 'this/is/my/string';
var result = s.split('/')[0];

// now capitalize first letter
result = result.substring(0,1).toUpperCase() + result.substring(1);

console.log(result); // prints "This"

JSBin: http://jsbin.com/puwabubaza/edit?js,console

Upvotes: 3

motanelu
motanelu

Reputation: 4025

Make sure the string is defined!

var string = 'This/is/test'

string = string.slice(0, string.indexOf('/'));
var result = string.charAt(0).toUpperCase() + string.slice(1);

console.log(result)

Upvotes: -1

Related Questions