Vivek ab
Vivek ab

Reputation: 680

remove all characters of a string after 5th character?

I need to remove all characters of a string after 5th character, for example

my string is

P-CI-7-C-71

and the output should be like

P-CI-

Upvotes: 1

Views: 1059

Answers (5)

BOBIN JOSEPH
BOBIN JOSEPH

Reputation: 1022

Use Can use substring function in the JS

the Substring(StringName,StartPosition, End Position);

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

Use substring

alert("P-CI-7-C-71".substring(0, 5)); 

So you can use it like

var str='P-CI-7-C-71'.substring(0, 5); 

You can also use substr, that will work the same in this case but remember they work differently so they are not generally interchangeable

var str='P-CI-7-C-71'.substr(0, 5); 

Difference can be noticed in the prototype

str.substring(indexStart[, indexEnd])

VS

str.substr(start[, length])

Upvotes: 1

Parth Patel
Parth Patel

Reputation: 521

Extracting String Parts

There are 3 methods for extracting a part of a string:

slice(start, end)
substring(start, end)
substr(start, length)

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Try this:

alert('P-CI-7-C-71'.substring(0,5));

var str = 'P-CI-7-C-71';
var res = str.slice(0,5);
alert(res);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386600

With String#substring:

The substring() method returns a subset of a string between one index and another, or through the end of the string.

document.write('P-CI-7-C-71'.substring(0, 5));

Upvotes: 0

Related Questions