From 7678a950cddd87fdad5222a8593702b32562b68d Mon Sep 17 00:00:00 2001 From: Felipe Elia Date: Thu, 7 Nov 2024 11:17:54 -0300 Subject: [PATCH] Escape special chars on Instant Results and Autosuggest --- assets/js/instant-results/components/results/result.js | 3 ++- assets/js/utils/helpers.js | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/assets/js/instant-results/components/results/result.js b/assets/js/instant-results/components/results/result.js index 47806c591d..2bc7dbc031 100644 --- a/assets/js/instant-results/components/results/result.js +++ b/assets/js/instant-results/components/results/result.js @@ -8,6 +8,7 @@ import { WPElement } from '@wordpress/element'; */ import { postTypeLabels } from '../../config'; import { formatDate } from '../../utilities'; +import { escapeRegExp } from '../../../utils/helpers'; import Result from '../common/result'; /** @@ -36,7 +37,7 @@ export default ({ hit, searchTerm, highlightTag }) => { /** * Note: highlighting is redone here because the unified highlight type is not supported in ES5 */ - const regex = new RegExp(`\\b(${searchTerm})`, 'gi'); + const regex = new RegExp(`\\b(${escapeRegExp(searchTerm)})`, 'gi'); let title; if (highlightTag === '' || highlightTag === undefined) { diff --git a/assets/js/utils/helpers.js b/assets/js/utils/helpers.js index 294947df7a..fec7b39942 100644 --- a/assets/js/utils/helpers.js +++ b/assets/js/utils/helpers.js @@ -47,7 +47,10 @@ export const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\ * @returns {string} replaced string */ export const replaceGlobally = (string, term, replacement) => { - return string.replace(new RegExp(escapeRegExp(term), 'g'), replacement); + return string.replace( + new RegExp(escapeRegExp(term), 'g'), + JSON.stringify(replacement).slice(1, -1), // Escapes especial chars and remove quotes added by JSON.stringify + ); }; /**