@@ -257,22 +257,24 @@ window.onkeydown = (e) => {
257257} ;
258258
259259function getSearchContext ( keyword ) {
260- let result = [ ] ;
260+ let results = [ ] ;
261+ // 遍历 searchJson 数组
261262 searchJson . forEach ( item => {
262- let title = item . title ;
263- let content = item . content . trim ( ) . replace ( / < [ ^ > ] + > / g, "" ) . replace ( / [ ` # \n ] / g, "" ) ;
264- if ( title . toLowerCase ( ) . indexOf ( keyword . toLowerCase ( ) ) !== - 1 || content . toLowerCase ( ) . indexOf ( keyword . toLowerCase ( ) ) !== - 1 ) {
265- result . push ( {
266- title : title ,
267- snippet : content . substring ( 0 , 100 ) + '...' ,
268- url : item . url
269- } ) ;
270- }
271- let snippet = content . substring ( 0 , 100 ) + '...' ;
272- result . push ( { title, snippet} )
273- } )
274- return result ;
275- }
263+ // 如果不存在 title 或 content,则跳过
264+ if ( ! item . title || ! item . content ) return ;
265+ let title = item . title ;
266+ // 确保 item.content 存在后再调用 trim(),否则可以设置为空字符串
267+ let content = item . content ? item . content . trim ( ) . replace ( / < [ ^ > ] + > / g, "" ) . replace ( / [ ` # \n ] / g, "" ) : "" ;
268+ if ( title . toLowerCase ( ) . indexOf ( keyword . toLowerCase ( ) ) !== - 1 ||
269+ content . toLowerCase ( ) . indexOf ( keyword . toLowerCase ( ) ) !== - 1 ) {
270+ // 使用文章内容的前 100 个字符作为摘要
271+ let snippet = content . slice ( 0 , 100 ) + '...' ;
272+ results . push ( { title, snippet } ) ;
273+ }
274+ } ) ;
275+ return results ;
276+ }
277+
276278
277279function searchFromKeyWordEnhanced ( keyword = "" ) {
278280 const context = getSearchContext ( keyword ) ; // 获取当前搜索上下文
0 commit comments