我有一個這樣的markdown字串
應用程式[TODO應用程式](url.com/apps/list?appid=q1w2e3)的狀態已被改變為完成。
我想用<mark></mark>來包裝搜索到的詞(見下面的函式),但跳過鏈接(url.com/apps/list? appid=q1w2e3)所以我將有TODO <mark>app</mark>但沒有url.com/<mark>app</mark>s/list?<mark>app</mark>id=q1w2e3
我怎樣才能實作這一點?
我用來添加marks的代碼:
const garbage = /[|{}()[]^$ *?]/g;
const highlightMarkdown = (originalString = '', highlight = ' ) => {
highlight = highlight.trim()。
if (!highlight) return originalString;
const wordsToFind = highlight.replace(garbage, ' ').split(')。
const result = wordsToFind.reduce((result, word) => {
const re = new RegExp(`(${word})`。'gi')。)
return result. replace(re, (word) => `<mark>${word}</mark>`)。)
}, originalString)。
return result;
};
const result = highlightMarkdown(
`Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.`,
'app'.
);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
UPD標記不僅app,而且<mark>app</mark>s,因為這個功能是為了用戶的搜索
uj5u.com熱心網友回復:
確保該詞前面/后面沒有字母數字,也沒有一些特定的字符如/, &, =和-,可能就足夠了。
另外,你可以用一個 regex來做這件事,而且不需要一個回呼作為replace呼叫的引數。你可以使用一個回呼$&:
const garbage = /[|{}()[]^$ *?]/g;
const highlightMarkdown = (originalString = '', highlight = ' ) => {
highlight = highlight.trim().replace(garbage, '') 。
if (!highlight) return originalString;
const wordsToFind = highlight.replace(/g, '|') 。
const re = new RegExp(`(? <! [/=&-])(${wordsToFind})(?! [/=&-])`, 'gi'/span>)。
return originalString.replace(re, '<mark>$&</mark> ')。
};
const result = highlightMarkdown(
`Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.`,
'app'.
);
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以去掉標志g,但它只會改變第一個app的匹配,而不是括號內的[TODO app]。
const garbage = /[|{}()[]^$ *?]/g;
const highlightMarkdown = (originalString = '', highlight = '') => {
highlight = highlight.trim()。
if (!highlight) return originalString;
const wordsToFind = highlight.replace(garbage, ' ').split(')。
let times = 0; //define here.
const result = wordsToFind.reduce((result, word) => {
const re = new RegExp(`(${word})`。'gi')。)
return result.replace(re, (word) =>/span> {
if(times<2){
times ; //增量這里。
return `<mark>${word}</mark> `;
}
return word。
});
}, originalString)。
return result;
};
const result = highlightMarkdown(
`Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.`,
'app'.
);
console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
更好的解決方案是使用單詞邊界
const re = new RegExp(`b(${word})`b`, 'gi')。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/323763.html
標籤:
