You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在文档库的卡片HTML长字符串中查找多个子字符串

Solution for Searching Multiple Substrings in HTML Card Strings

Got it, let's break down how to handle searching multiple substrings in those long HTML card strings you're building for your document library. Here are a few practical approaches tailored to your use case:

1. Native String Methods (Simple Exact Matches)

If you just need to check for exact substring presence or find their positions, JavaScript's built-in includes() and indexOf() methods are straightforward and efficient.

// Your generated card HTML string
const cardHtml = '<div class="cardBox col-lg-4 col-md-6 col-sm-12"><div class="card" style="margin-bottom: 1em;"><img class="card-img-top" src="' + data.values[n][5] + '" alt="Card image cap"><div class="card-body"><h5 class="card-title">' + data.values[n][0] + '</h5><h6 class="doctype card-subtitle mb-2 text-muted">' + data.values[n][3] + '</h6...';

// List of substrings to search for
const searchTerms = ['card-title', 'annual-report', '2024'];

// Check if all terms exist in the string
const allTermsFound = searchTerms.every(term => cardHtml.includes(term));

// Filter to get only found terms
const foundTerms = searchTerms.filter(term => cardHtml.includes(term));

// Get positions of each term
searchTerms.forEach(term => {
  const position = cardHtml.indexOf(term);
  if (position !== -1) {
    console.log(`Found "${term}" at index ${position}`);
  } else {
    console.log(`"${term}" not present in the card`);
  }
});

Pros: No extra setup, fast for basic checks.
Cons: Doesn't handle pattern matching (like case insensitivity) and can accidentally match substrings in HTML attributes (e.g., a class name) instead of content.

2. Regular Expressions (Complex Pattern Matching)

For flexible searches—like case-insensitive matches, partial patterns, or wildcard use—regular expressions are the way to go.

const cardHtml = '<div class="cardBox col-lg-4 col-md-6 col-sm-12"><div class="card" style="margin-bottom: 1em;"><img class="card-img-top" src="' + data.values[n][5] + '" alt="Card image cap"><div class="card-body"><h5 class="card-title">' + data.values[n][0] + '</h5><h6 class="doctype card-subtitle mb-2 text-muted">' + data.values[n][3] + '</h6...';

// Define regex patterns (use RegExp.escape() for terms with special characters)
const searchPatterns = [
  /card-title/g,               // Global match for the class name
  /pdf|PDF|document/g,         // Match any of these document types (case-insensitive alternative: /pdf|document/i)
  /20\d{2}/g                   // Match any 20XX year
];

// Check each pattern and collect matches
searchPatterns.forEach(pattern => {
  const matches = cardHtml.match(pattern);
  if (matches) {
    console.log(`Matches for ${pattern}:`, matches);
  } else {
    console.log(`No matches found for ${pattern}`);
  }
});

// Verify all patterns have matches
const allPatternsMatch = searchPatterns.every(pattern => pattern.test(cardHtml));

Pros: Supports advanced matching logic.
Cons: Requires understanding regex syntax, and you need to escape special characters (e.g., . becomes \.) to avoid unintended matches.

3. Parse HTML to DOM (Most Reliable for Structured Content)

Since your string is valid HTML, parsing it into a DOM element lets you search based on structure (e.g., find text inside a .card-title element) rather than raw strings. This avoids false positives from attribute values.

const cardHtml = '<div class="cardBox col-lg-4 col-md-6 col-sm-12"><div class="card" style="margin-bottom: 1em;"><img class="card-img-top" src="' + data.values[n][5] + '" alt="Card image cap"><div class="card-body"><h5 class="card-title">' + data.values[n][0] + '</h5><h6 class="doctype card-subtitle mb-2 text-muted">' + data.values[n][3] + '</h6...';

// Create a temporary DOM element to parse the HTML
const tempContainer = document.createElement('div');
tempContainer.innerHTML = cardHtml;

// Define what you want to search for (structured targets)
const searchTargets = [
  { type: 'element', selector: '.card-title' }, // Check if the title element exists
  { type: 'text', selector: '.doctype', content: 'pdf' }, // Check if doctype contains "pdf"
  { type: 'attribute', selector: 'img', attr: 'src', contains: '.png' } // Check if img src has .png
];

// Execute searches and collect results
const searchResults = searchTargets.map(target => {
  let found = false;
  switch(target.type) {
    case 'element':
      found = tempContainer.querySelector(target.selector) !== null;
      break;
    case 'text':
      const element = tempContainer.querySelector(target.selector);
      found = element ? element.textContent.includes(target.content) : false;
      break;
    case 'attribute':
      const img = tempContainer.querySelector(target.selector);
      found = img ? img.getAttribute(target.attr).includes(target.contains) : false;
      break;
  }
  return { target, found };
});

console.log('Structured search results:', searchResults);

Pros: Precise, structure-aware searches—perfect for your card HTML setup.
Cons: Slightly more code, but worth it for avoiding false matches.

Which to Choose?

  • Use native string methods for simple exact matches.
  • Use regex when you need pattern-based flexibility.
  • Use DOM parsing when you need to search within specific HTML elements or attributes (this is my top recommendation for your card library use case).

内容的提问来源于stack exchange,提问作者Karie Adair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:57