Solved

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

Posted on 2008-10-30
5
450 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
ID: 22840423

<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
ID: 22840856
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
ID: 22842457
StartsWith is a prototype.
sourcestring = (sourcestring.substr(0,1)=='-' ) ? sourcestring.substring(1):sourcestring;

Open in new window

0
 
LVL 51

Expert Comment

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

Expert Comment

by:ddrudik
ID: 22852570
Thanks for the question and the points.
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
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…

770 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