简体   繁体   中英

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%"

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.


That's not the question. Is there something like that [%] in jQuery?

I have the following code.

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

Many times, my JSON might return something like this:

nameofimage. jpg?1

This is ignored because jpg?1 is NOT equals to jpg but it is still a 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():

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". The above method would consider it as a "jpg" where as it is not. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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