Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get string before a character

Tags:

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?

like image 501
Keith Power Avatar asked Aug 25 '12 18:08

Keith Power


People also ask

How do you get a string before a specific character in JavaScript?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How can I get part of a string in JavaScript?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do you slice a string upto a certain character in JavaScript?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.


Video Answer


2 Answers

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

like image 55
3on Avatar answered Sep 22 '22 06:09

3on


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(""); } 
like image 33
jfriend00 Avatar answered Sep 20 '22 06:09

jfriend00