Skip to content

Instantly share code, notes, and snippets.

@voscausa
Last active September 25, 2019 20:05
Show Gist options
  • Save voscausa/e9298e63ce528585c9f8a920d6d79edb to your computer and use it in GitHub Desktop.
Save voscausa/e9298e63ce528585c9f8a920d6d79edb to your computer and use it in GitHub Desktop.
Search a text in a table column in Svelte 3 and mark te results
<script>
import Row from "./Row.svelte";
async function getData() {
// get json data: list of row objects like [{id: .., text: ..} ....]
// we use a list of objects because it has a list order and the object can be easely expanded
const res = await fetch("./row_data.json");
return await res.json();
}
let search = "";
function searchHandler(e) {
search = e.target.value;
}
</script>
<style>
table,
th {
border-collapse: collapse;
border: 1px solid black;
}
</style>
<h3>
Reactive column search
<!-- <input bind:value={$search}> -->
<input on:blur={searchHandler} />
</h3>
<table>
<tr>
<th>Row</th>
<th>Found</th>
<th>Text</th>
</tr>
{#await getData() then data}
{#each data as item}
<Row row={item} {search} />
{/each}
{/await}
</table>
<script>
export let row;
export let search = '';
let result = row.text;
let found = false;
function searchNow(s) {
let re = new RegExp(s, 'gi');
result = row.text.replace(re, `<mark>${s}</mark>`);
found = s !== '' && row.text !== result;
}
$: searchNow(search)
</script>
<style>
td {
border: 1px solid black;
}
</style>
<tr>
<td>{row.id}</td>
<td>{found}</td>
<td>{@html result}</td>
</tr>
[
{"id": "A", "text": "Dit is een stuk tekst uit een veel grotere tekst"},
{"id": "B","text": "En hier nog een stuk tekst !!"}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment