javascript get string before a character

前端 未结 4 1288
心在旅途
心在旅途 2021-02-05 05:16

I have a string that and I am trying to extract the characters before the quote.

Example is extract the 14 from 14\' - €14.99

I

相关标签:
4条回答
  • 2021-02-05 05:40

    try this

    str.substring(0,str.indexOf("'"));
    
    0 讨论(0)
  • 2021-02-05 05:42

    Nobody seems to have presented what seems to me as the safest and most obvious option that covers each of the cases the OP asked about so I thought I'd offer this:

    function getCharsBefore(str, chr) {
        var index = str.indexOf(chr);
        if (index != -1) {
            return(str.substring(0, index));
        }
        return("");
    }
    
    0 讨论(0)
  • 2021-02-05 06:01

    Here is an underscore mixin in coffescript

    _.mixin
      substrBefore : ->
        [char, str] = arguments
        return "" unless char?
        fn = (s)-> s.substr(0,s.indexOf(char)+1)
        return fn(str) if str?
        fn
    

    or if you prefer raw javascript : http://jsfiddle.net/snrobot/XsuQd/

    You can use this to build a partial like:

    var beforeQuote = _.substrBefore("'");
    var hasQuote = beforeQuote("14' - €0.88"); // hasQuote = "14'"
    var noQoute  = beforeQuote("14 €0.88");    // noQuote =  ""
    

    Or just call it directly with your string

    var beforeQuote = _.substrBefore("'", "14' - €0.88"); // beforeQuote = "14'"
    

    I purposely chose to leave the search character in the results to match its complement mixin substrAfter (here is a demo: http://jsfiddle.net/snrobot/SEAZr/ ). The later mixin was written as a utility to parse url queries. In some cases I am just using location.search which returns a string with the leading ?.

    0 讨论(0)
  • 2021-02-05 06:03

    This is the what you should use to split:

    string.slice(0, string.indexOf("'"));
    

    And then to handle your non existant value edge case:

    function split(str) {
     var i = str.indexOf("'");
    
     if(i > 0)
      return  str.slice(0, i);
     else
      return "";     
    }
    

    Demo on JsFiddle

    0 讨论(0)
提交回复
热议问题