简体   繁体   English

如何在 JavaScript 中获取指定字符之前的子字符串?

[英]How to grab substring before a specified character in JavaScript?

I am trying to extract everything before the ',' comma.我正在尝试提取“,”逗号之前的所有内容。 How do I do this in JavaScript or jQuery?如何在 JavaScript 或 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, '.')); 
var streetaddress = addy.substr(0, addy.indexOf(',')); 

虽然它不是获取有关每种方法作用的确切信息的最佳位置( mozilla 开发人员网络对此更好)但w3schools.com非常适合向您介绍语法。

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

尝试这个:

streetaddress.substring(0, streetaddress.indexOf(','));
//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.此外,我建议您使用 camel-case(streetAddress) 命名您的变量,以获得更好的可读性。

如果您喜欢简短,只需使用RegExp

var streetAddress = /[^,]*/.exec(addy)[0];

almost the same thing as David G's answer but without the anonymous function, if you don't feel like including one.与大卫 G 的答案几乎相同,但没有匿名功能,如果您不想包含一个。

s = s.substr(0, s.indexOf(',') === -1 ? s.length : s.indexOf(','));

in this case we make use of the fact that the second argument of substr is a length, and that we know our substring is starting at 0.在这种情况下,我们利用substr的第二个参数是一个长度这一事实,并且我们知道我们的子字符串从 0 开始。

the top answer is not a generic solution because of the undesirable behavior if the string doesn't contain the character you are looking for.最佳答案不是通用解决方案,因为如果字符串不包含您要查找的字符,则会出现不良行为。

if you want correct behavior in a generic case, use this method or David G's method, not the top answer如果您想在一般情况下正确行为,请使用此方法或 David G 的方法,而不是最佳答案

regex and split methods will also work, but may be somewhat slower / overkill for this specific problem.正则表达式和拆分方法也可以工作,但对于这个特定问题可能会有点慢/过大。

You can also use shift() .您也可以使用shift()

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

According to MDN Web Docs:根据 MDN 网络文档:

The shift() method removes the first element from an array and returns that removed element. shift()方法从数组中删除第一个元素并返回删除的元素。 This method changes the length of the array.此方法更改数组的长度。

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

var newString = string.substr(0,string.indexOf(','));
var streetaddress = addy.substr(0, addy.indexOf('.')); 

(您应该阅读javascript 教程,尤其是关于字符串函数的部分)

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,',');

You could use regex as this will give you the string if it matches the requirements.您可以使用正则表达式,因为如果它符合要求,它将为您提供字符串。 The code would be something like:代码将类似于:

const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);

console.log(matchedResult[0]); // This will give you 1345 albany street.

So to break the code down.所以要分解代码。 [1-9][0-9]* basically means the first number cannot be a zero and has to be a number between 1-9 and the next number can be any number from 0-9 and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [1-9][0-9]*基本上意味着第一个数字不能为零,必须是1-9之间的数字,下一个数字可以是0-9之间的任何数字,并且可以出现零次或多次有时数字只是一个数字,然后它匹配一个空格。 [a-zA-Z] basically matches all capital letters to small letters and has to occur one or more times and this is repeated. [a-zA-Z]基本上将所有大写字母与小写字母匹配,并且必须出现一次或多次,并且重复。

You can use Azle to get substrings before : 您可以使用AZLE获得子之前

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 结果 :我们转到

If you are worried about catching the case where no comma is present, you could just do this:如果您担心遇到没有逗号的情况,您可以这样做:

var end = Math.min(addy.indexOf(","), addy.length)
var streetaddress = addy.substr(0, end);

Nobody said it had to go on one line.没有人说它必须放在一条线上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM