Skip to content

Commit

Permalink
Merge pull request #3999 from 10up/fix/issue-3968
Browse files Browse the repository at this point in the history
Escape special chars on Instant Results and Autosuggest
  • Loading branch information
felipeelia authored Nov 7, 2024
2 parents d57b135 + 7678a95 commit c702b78
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 c702b78

Please sign in to comment.