Skip to content

Commit

Permalink
Merge pull request #10390 from ckeditor/ck/10131-whole-search-with-sp…
Browse files Browse the repository at this point in the history
…aces

Fix (find-and-replace): Allows search term to contain trailing/leading space when searching "whole words only". Closes #10131.
  • Loading branch information
niegowski committed Aug 23, 2021
2 parents daffcd7 + fc4e74e commit fd9dfa7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/ckeditor5-find-and-replace/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ function regexpMatchToFindResult( matchResult ) {
let startOffset = matchResult.index;

// Searches with match all flag have an extra matching group with empty string or white space matched before the word.
// If the search term starts with the space already, there is no extra group even with match all flag on.
if ( matchResult.length === 3 ) {
startOffset += matchResult[ 1 ].length;
}
Expand Down Expand Up @@ -138,7 +139,13 @@ export function findByTextCallback( searchTerm, options ) {
if ( options.wholeWords ) {
const nonLetterGroup = '[^a-zA-Z\u00C0-\u024F\u1E00-\u1EFF]';

regExpQuery = `(^|${ nonLetterGroup }|_)` + regExpQuery + `(?:_|${ nonLetterGroup }|$)`;
if ( !new RegExp( '^' + nonLetterGroup ).test( searchTerm ) ) {
regExpQuery = `(^|${ nonLetterGroup }|_)${ regExpQuery }`;
}

if ( !new RegExp( nonLetterGroup + '$' ).test( searchTerm ) ) {
regExpQuery = `${ regExpQuery }(?:_|${ nonLetterGroup }|$)`;
}
}

const regExp = new RegExp( regExpQuery, flags );
Expand Down
24 changes: 24 additions & 0 deletions packages/ckeditor5-find-and-replace/tests/findcommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,30 @@ describe( 'FindCommand', () => {
expect( results.length ).to.equal( 1 );
} );

it( 'set to true matches a text ending with a space ', () => {
editor.setData( '<p>foo bar baz</p>' );

const { results } = command.execute( 'bar ', { wholeWords: true } );

expect( results.length ).to.equal( 1 );
} );

it( 'set to true matches a text starting with a space ', () => {
editor.setData( '<p>foo bar baz</p>' );

const { results } = command.execute( ' bar', { wholeWords: true } );

expect( results.length ).to.equal( 1 );
} );

it( 'set to true matches a text starting and ending with a space ', () => {
editor.setData( '<p>foo bar baz</p>' );

const { results } = command.execute( ' bar ', { wholeWords: true } );

expect( results.length ).to.equal( 1 );
} );

it( 'set to true doesn\'t match a word including diacritic characters', () => {
editor.setData( '<p>foo łbarę and Äbarè</p>' );

Expand Down

0 comments on commit fd9dfa7

Please sign in to comment.