[英]How can I remove all characters after a specified word and before a period in a string using javascript?
我有這個字符串:
1_plex_light-blue-striped_imagegroup.jpg?v=1581100432
有時它看起來像這樣:
1_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432
該字符串由不同的位組成,我的代碼使用這些位來幫助決定顯示圖像的位置和時間。
代碼:
此代碼位於單擊顏色框時觸發的函數內。 我傳入被單擊的框的顏色,后跟單詞“_imagegroup”,並使用該字符串來幫助過濾具有從我開始使用的圖像組中選擇的顏色的圖像。
var imagesArray = makeProductImagesArray();
function filterImageByColourAndGroupType(image) {
return image.masterImagePath.includes(`${colour}_imageset.`);
}
var filteredArray = imagesArray.filter(filterImageByColourAndGroupType);
filteredArray.sort((a, b) => a.masterImagePath.replace(/\D/g,'').localeCompare(b.masterImagePath.replace(/\D/g,'')));
問題:
有時匹配失敗是因為像“d6f347cf-1440-45ef-955d-144ge18d0a00”這樣的隨機字符串被添加到圖像路徑中。
我怎樣才能確保我的過濾器只給我匹配這種格式的圖像:
light-blue-striped_imagegroup.
過濾器需要認為在“imagegroup”之后添加的字符串不存在。 它會看到這個:
1_plex_light-blue-striped_imagegroup.jpg?v=1581100432
並完全忽略:
_d6f347cf-1440-45ef-955d-144ge18d0a00
提前致謝
您可以使用Lookbehind assertion
來匹配圖像組前面的字符:
const str = '1_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432'; console.log(str); const regex = "/(?<=imagegroup).*\\./" const newStr = str.replace(regex, '.'); console.log(newStr)
編輯: Lookbehind assertion
具有(?<=y)x
的形式,並且僅當“x”以“y”開頭時才匹配“x”,舉一個簡單的例子:
const str = 'matchNOT but matchTHIS'; //this will look for anything containing the word 'match', //but only if it's preceded by the word 'but'; so 'match' before 'but' will be ignored // and 'match' after 'but' will be captured. const newStr = str.match(/(?<=but).*match.*/); console.log(newStr)
您可以使用正則表達式。 像這樣的事情會起作用:
function filterImageByColourAndGroupType(image) {
const regex = new RegExp(`[0-9]+_.*_${colour}_imagegroup[_.*]?`);
return image.masterImagePath.match(regex) != null;
}
這將匹配1_plex_light-blue-striped_imagegroup.jpg?v=1581100432
和1_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432
您可能需要根據值的特定約束(我不知道,我只是在這里猜測)稍微調整一下確切的正則表達式,但這應該會讓您開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.