skip to Main Content

I have a string in JavaScript like var s="test - test1" and sometimes s=" - test1" and sometimes just " -". I want to remove the space and hyphen only if it’s present at the start and end of the string. Meaning, we should not do anything for the 1st case s="test - test1".

Expected Result:

var s="test - test1"

result should be "test - test1"

var s=" - test1"

result should be "test1"

" -"

result should be ""

Could you guys help me on this?

3

Answers


  1. I assume you want to remove all spaces with the following hyphens, then just replace it with this method .replace(/ -/g,'').

    var s="test - test1";
    console.log(s.replace(/ -/g,''))
    s = " - test1";
    console.log(s.replace(/ -/g,''))
    s = " -";
    console.log(s.replace(/ -/g,''))
    s="test - test1 - test2";
    console.log(s.replace(/ -/g,''))
    Login or Signup to reply.
  2.   
    var s="test - test1";
    var reg = new RegExp(/-$|^-/ig);
    console.log(s.trim().replace(reg,"").trim());
    Login or Signup to reply.
  3. A regex-only solution (try-its were modified a bit to avoid messing with line breaks):

    function removeLeadingTrailingHyphens_match(s) {
      return s.match(/^(?:s*-s*)?(.*?)(?:s*-s*)?$/)[1];
    }
    

    Try it on regex101.com.

    …or, using .replace():

    function removeLeadingTrailingHyphens_replace(s) {
      return s.replace(/^s*-s*|s*-s*$/);
    }
    

    Try it on regex101.com.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search