Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove characters from string

Status
Not open for further replies.

thankgodfortektips

Programmer
Joined
Dec 20, 2005
Messages
95
Location
KY
Hey All, I have a asp page that has a field that displays a string such as 1234/0/16/0. I need to be able to take this string, remove the number after the first /, add 1 to this number, then put it back in the string.

So 1234/0/16/0 will end up being 1234/1/16/0.

Thanks in advance guys!

 
a split ought to do that for you
Code:
var numString = '1234/0/16/0';

var numArray = numString.split('/');

var newNum = numArray[0] + "/" + (parseInt(numArray[1]) + 1) + "/" + numArray[2] + "/" + numArray[3];

that is untested and could probably be consolodated a bit more, but maybe something along those lines.

=========================================
Don't sweat the petty things and don't pet the sweaty things.
 
Are all of your strings going to be 4 segments long (i.e. always [tt]x1/x2/x3/x4[/tt], never [tt]x1/x2/x3[/tt] or [tt]x1/x2/x3/x4/x5[/tt] )?
If they are, then NorthStarDA's code (above) should be perfect for what you're needing; if not, let us know & someone can work up a function that'll work on a string with a variable number of segments for you.




I hope this helps;
Rob Hercules
 
My suggestion will actually add an extra line of code, so I don't know that it's necessarily good for this situation. However, in the event that your string had 1000 slashes in it, this would cut down your code considerably:
Code:
[b]using NorthStarDA's code:[/b]

var numString = '1234/0/16/0';
var numArray = numString.split('/');
[gray]//it's good habit to always put a 10 in for the second argument 
//when using parseInt with decimal numbers[/gray]
numArray[1] = parseInt(numArray[1][!], 10[/!]) + 1;
var newNum = numArray[!].join("/")[/!];

-kaht

[small] <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
[banghead] [small](He's back)[/small]
 
or a regex:

var numString = '1234/12/16/0';
alert(numString.replace(/\/[\d]+/,"/1"))


Known is handfull, Unknown is worldfull
 
Hey all, just one more question... I need to adapt the code above to just take out the numbers after the first / then add one

So from 1234/9/16/0 I would end up with 10

Thanks again!
 
no adaptation necessary, the variable numArray[1] holds exactly that value

=========================================
Don't sweat the petty things and don't pet the sweaty things.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top