Skip to content

Commit b9c312d

Browse files
Creating function that gets rid of HTML entities
1 parent 863134a commit b9c312d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

components/content-search/utils.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { WP_REST_API_User, WP_REST_API_Search_Result } from 'wp-types';
33
import apiFetch from '@wordpress/api-fetch';
44
import { addQueryArgs } from '@wordpress/url';
5+
import { decodeEntities } from '@wordpress/html-entities';
56
import type { ContentSearchMode, QueryFilter } from './types';
67

78
interface IdentifiableObject extends Object {
@@ -83,6 +84,23 @@ interface NormalizeResultsArgs {
8384
excludeItems: Array<IdentifiableObject>;
8485
}
8586

87+
/**
88+
* Convert a WP "rendered" title (which can contain HTML + entities) into plain text.
89+
* - Strips any HTML tags.
90+
* - Decodes HTML entities.
91+
* - Normalizes NBSP and trims.
92+
*/
93+
export const toPlainTextTitle = (input: string | undefined | null): string => {
94+
if (!input) {
95+
return '';
96+
}
97+
98+
const doc = new DOMParser().parseFromString(String(input), 'text/html');
99+
const text = doc.body.textContent ?? '';
100+
101+
return decodeEntities(text).replace(/\u00A0/g, ' ').trim();
102+
};
103+
86104
/*
87105
* Depending on the mode value, this method normalizes the format
88106
* of the result array.

0 commit comments

Comments
 (0)