Get everything after the dash in a string in javascript

前端 未结 9 2024
故里飘歌
故里飘歌 2020-11-30 22:47

What would be the cleanest way of doing this that would work in both IE and firefox.

My string looks like this: sometext-20202

Now the \'sometext\' and the

相关标签:
9条回答
  • 2020-11-30 23:07
    var the_string = "sometext-20202";
    var parts = the_string.split('-', 2);
    
    // After calling split(), 'parts' is an array with two elements:
    // parts[0] is 'sometext'
    // parts[1] is '20202'
    
    var the_text = parts[0];
    var the_num  = parts[1];
    
    0 讨论(0)
  • 2020-11-30 23:10

    You can do it with built-in RegExp(pattern[, flags]) Factory Notation in js like this:

    RegExp(/-(.*)/).exec("sometext-20202")[1]
    

    in above code exec function will return an array with two elements (["-20202", "20202"]) one with hyphen(-20202) and one without hyphen(20202) , you should pick second element (index 1)

    0 讨论(0)
  • 2020-11-30 23:11

    Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.

    0 讨论(0)
  • 2020-11-30 23:13

    AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).

    Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.

    0 讨论(0)
  • 2020-11-30 23:14

    How I would do this:

    // function you can use:
    function getSecondPart(str) {
        return str.split('-')[1];
    }
    // use the function:
    alert(getSecondPart("sometext-20202"));
    
    0 讨论(0)
  • 2020-11-30 23:19
    var testStr = "sometext-20202"
    var splitStr = testStr.substring(testStr.indexOf('-') + 1);
    
    0 讨论(0)
提交回复
热议问题