Keith Power
Keith Power

Reputation: 14141

javascript get string before a character

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 am using the follwing code to acheive this.

$menuItem.text().match(/[^']*/)[0]

My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.

What I am I doing wrong with the match?

Upvotes: 26

Views: 73793

Answers (5)

akituti
akituti

Reputation: 41

I use "split":

let string = "one-two-three";

let um = string.split('-')[0];
let dois = string.split('-')[1];
let tres = string.split('-')[2];

document.write(tres) //three

Upvotes: 0

3on
3on

Reputation: 6339

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

Upvotes: 41

jhnstn
jhnstn

Reputation: 2518

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 ?.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707326

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("");
}

Upvotes: 6

nandu
nandu

Reputation: 779

try this

str.substring(0,str.indexOf("'"));

Upvotes: 5

Related Questions