How to grab substring before a specified character

2020-01-24 10:34发布

I am trying to extract everything before the ',' comma. How do I do this in JavaScript or jQuery? I tried this and not working..

1345 albany street, Bellevue WA 42344

I just want to grab the street address.

var streetaddress= substr(addy, 0, index(addy, '.')); 

12条回答
趁早两清
2楼-- · 2020-01-24 11:14

You can use Azle to get substrings before:

str = 'This is how we go to the place!'

az.get_everything_before(str, 'place')

Result: This is how we go to the

after

str = 'This is how we go to the place!'

az.get_everything_after(str, 'go')

Result: to the place!

and in between:

str = 'This is how we go to the place!'

az.get_everything_between(str, 'how', 'place')

Result: we go to the

查看更多
老娘就宠你
3楼-- · 2020-01-24 11:15

You can also use shift().

var streetaddress = addy.split(',').shift();

According to MDN Web Docs:

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

查看更多
不美不萌又怎样
4楼-- · 2020-01-24 11:18
//split string into an array and grab the first item

var streetaddress = addy.split(',')[0];

Also, I'd recommend naming your variables with camel-case(streetAddress) for better readability.

查看更多
做自己的国王
5楼-- · 2020-01-24 11:21

If you want to return the original string untouched if it does not contain the search character then you can use an anonymous function (a closure):

var streetaddress=(function(s){var i=s.indexOf(',');
   return i==-1 ? s : s.substr(0,i);})(addy);

This can be made more generic:

var streetaddress=(function(s,c){var i=s.indexOf(c);
   return i==-1 ? s : s.substr(0,i);})(addy,',');
查看更多
一夜七次
6楼-- · 2020-01-24 11:22

If you like it short simply use a RegExp:

var streetAddress = /[^,]*/.exec(addy)[0];
查看更多
ゆ 、 Hurt°
7楼-- · 2020-01-24 11:30
var streetaddress = addy.substr(0, addy.indexOf('.')); 

(You should read through a javascript tutorial, esp. the part about String functions)

查看更多
登录 后发表回答