Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

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

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
Hojoformo
Asked:
Hojoformo
1 Solution
 
ddrudikCommented:

<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
 
SRigneyCommented:
You don't need a regular expression for this.

if ( sourcestring !=null && sourcestring.length > 1 && sourcestring.startsWith("-") ) {
  sourcestring = sourcestring.substring(1);
}
0
 
MattKenefickCommented:
StartsWith is a prototype.
sourcestring = (sourcestring.substr(0,1)=='-' ) ? sourcestring.substring(1):sourcestring;

Open in new window

0
 
ahoffmannCommented:
yourstring=yourstring.replace(/\W(-)\w+/g,'');
0
 
ddrudikCommented:
Thanks for the question and the points.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now