Skip to content

Commit

Permalink
Escape special chars on Instant Results and Autosuggest
Browse files Browse the repository at this point in the history
  • Loading branch information
felipeelia committed Nov 7, 2024
1 parent 29b1f78 commit 7678a95
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
3 changes: 2 additions & 1 deletion assets/js/instant-results/components/results/result.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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) {
Expand Down
5 changes: 4 additions & 1 deletion assets/js/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
};

/**
Expand Down

0 comments on commit 7678a95

Please sign in to comment.