简体   繁体   English

如何检查字符串的一部分并接受其后的任何内容?

[英]How to check portion of a string and accept anything after it?

I had a hard time wording this question. 我很难写出这个问题。 Lets say you have two things in a database: 假设您在数据库中有两件事:

-"String" -“串”

-"Stringify" - “字符串”

In PHP, you use this: "SELECT * WHERE string = stri%" 在PHP中,您使用:“SELECT * WHERE string = stri%”

This would return both of the strings in the database because the % [percentage sign] is the responsible one for checking if the values have those four letters [stri] and accepting them since the rest doesn't matter. 这将返回数据库中的两个字符串,因为 [百分号]是负责检查值是否具有这四个字母[stri]并接受它们,因为其余的无关紧要。


That's not the question. 那不是问题。 Is there something like that [%] in jQuery? 在jQuery中有类似的东西[%]吗?

I have the following code. 我有以下代码。

if (ext == "jpg" || ext == "gif") {
} else {
   ext = ext + ".jpg";
}

Many times, my JSON might return something like this: 很多时候,我的JSON可能会返回如下内容:

nameofimage. nameofimage。 jpg?1 JPG?1

This is ignored because jpg?1 is NOT equals to jpg but it is still a jpg. 这被忽略,因为jpg?1 等于jpg,但它仍然是jpg。 This is why I am asking... Is there anything that can be used to check only the first three letters of the extension and ignore the rest? 这就是我要问的原因......有什么东西可以用来检查扩展名的前三个字母并忽略其余的字母吗?

Something like this: 像这样的东西:

if (ext == "jpg%" || ext == "gif%") {
//Do nothing, it's already a jpg or a gif
} else {
   ext = ext + ".jpg";
}

I tried my very best to word this the right way. 我尽力以正确的方式说出来。 I hope someone here can help me. 我希望这里有人可以帮助我。 Thank you. 谢谢。

尝试string.contains()

if(ext.contains(".jpg") || ext.contains(".gif")) {

I think the method you are looking for is indexOf(): 我认为您正在寻找的方法是indexOf():

if (ext.indexOf('jpg') !== -1 || ext.indexOf('gif') !== -1) {
    // true
}

However it is a bit cleaner and safer to not just check for the extension but the whole filename as well. 然而,不仅检查扩展名而且检查整个文件名,它更清洁,更安全。 Imagine this filename: "somejpg.exe". 想象一下这个文件名:“somejpg.exe”。 The above method would consider it as a "jpg" where as it is not. 上述方法会将其视为“jpg”,而不是。 The easiest to use regular expressions for these kind of things: 最容易使用这些事情的正则表达式:

/\.(jpg|gif|png|bmp)$/.test('test.png'); // => true
/\.(jpg|gif|png|bmp)$/.test('test.gif'); // => true
/\.(jpg|gif|png|bmp)$/.test('hack_jpg.exe'); // => false

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

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