javascript get string before a character

前端 未结 4 1391
心在旅途
心在旅途 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 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 ?.

提交回复
热议问题