Solved

Javascript Regular Expression for removing a "-" in first position of a word?

Posted on 2008-10-30
5
448 Views
Last Modified: 2008-10-31
I need the Javascript Regular Expression for removing a "-" in first position of a word?

For example, how would I remove the "-" from "-MyTest".  I only need to remove the dash if it is in the first position.  
0
Comment
Question by:Hojoformo
5 Comments
 
LVL 27

Accepted Solution

by:
ddrudik earned 500 total points
Comment Utility

<script type="text/javascript">

  var re = /^-/;

  var sourcestring = "-source string to match with pattern";

  var result = sourcestring.replace(re, "");

  alert("result = " + result);

</script>

Open in new window

0
 
LVL 15

Expert Comment

by:SRigney
Comment Utility
You don't need a regular expression for this.

if ( sourcestring !=null && sourcestring.length > 1 && sourcestring.startsWith("-") ) {
  sourcestring = sourcestring.substring(1);
}
0
 
LVL 4

Expert Comment

by:MattKenefick
Comment Utility
StartsWith is a prototype.
sourcestring = (sourcestring.substr(0,1)=='-' ) ? sourcestring.substring(1):sourcestring;

Open in new window

0
 
LVL 51

Expert Comment

by:ahoffmann
Comment Utility
yourstring=yourstring.replace(/\W(-)\w+/g,'');
0
 
LVL 27

Expert Comment

by:ddrudik
Comment Utility
Thanks for the question and the points.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Whatever be the reason, if you are working on web development side,  you will need day-today validation codes like email validation, date validation , IP address validation, phone validation on any of the edit page or say at the time of registration…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now