views:

107

answers:

5

I have a variable that reads as _123456 and I need to delete the underscore prefix on this variable before storing it to a field. How do I do this?

 var value = "_123456"
+4  A: 

This is just generic Javascript, not specific to jQuery. You'd do something like this:

var result = value.substring(1);

Or...

var result = value.replace(/^_/, '');

Or... (if there can be more than one underscore)

var result = value.replace(/^_+/, '');

Aistina
regex seems overkill for this..
Miky Dinescu
this is perfect thank you although Miky D is right...
sadmicrowave
+2  A: 

value.substr(1)

No need for jQuery!

Yassin
This is also good!, actually I like this method better than the regex method...seems less processor intensive...am I right?
sadmicrowave
Yes, of course!
Yassin
Your question made me think you where asking for all of the ways to achieve your goal rather than what is the preferred way.
Christopher Altman
+1  A: 
var value = "_123456"
var trimmed = value.substring(1); // "123456"
Greg
`value.substr(1)` will do the same thing.
Greg
A: 

[not recommended] To do this with jQuery (and an if):

var element = $('<div></div>'); 
var text = "_123456"; 
for(var i = 0; i < text.length; i++) { 
   if ( i > 0 ) {
      element.append('<span>' + text[i] + '</span>'); 
   }
}
var trimmed = element.text();

I tried element.remove(':first') instead of the if, but it didn't seem to work. No idea why.

ZeissS
way more work than I'm willing to put forth for this small of an issue...this solution is just too long... value.substring(1) is all I needed....
sadmicrowave
Sure, but u asked for jQuery and I thought it was fun to try :) Please note the "not recommended". I wouldn't do it this way neither.
ZeissS
A: 

FYI - If the underscore is after the digits then you could use parseInt()

var value = "123456_"  

So for example parseInt("123456_") will return the number 123456.

Christopher Altman