Skip to content

Commit

Permalink
Merge pull request #15280 from ckeditor/docs/word-ranges-how-to
Browse files Browse the repository at this point in the history
Add a new how-to for getting words and their ranges.
  • Loading branch information
godai78 authored Oct 31, 2023
2 parents 6398020 + 4ad9564 commit e55e955
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions docs/examples/how-tos.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,45 @@ for ( const value of range.getWalker() ) {
}
```

### How to find words in a document, and get their ranges?

If you need to search a text fragment and remap it to its model position, use the following example. It will find all words available in the document root, create a model range based on these and feed them into the console.

```js
const model = editor.model;
const rootElement = model.document.getRoot();
const rootRange = model.createRangeIn( rootElement );
const wordRanges = [];

for ( const item of rootRange.getItems() ) {
// Find `$block` elements (those accept text).
if ( item.is( 'element' ) && model.schema.checkChild( item, '$text' ) ) {
// Get the whole text from block.
// Inline elements (like softBreak or imageInline) are replaced
// with a single whitespace to keep the position offset correct.
const blockText = Array.from( item.getChildren() )
.reduce( ( rangeText, item ) => rangeText + ( item.is( '$text' ) ? item.data : ' ' ), '' );

// Find all words.
for ( const match of blockText.matchAll( /\b\S+\b/g ) ) {
// The position in a text node is always parented by the block element.
const startPosition = model.createPositionAt( item, match.index );
const endPosition = model.createPositionAt( item, match.index + match[ 0 ].length );

wordRanges.push( model.createRange( startPosition, endPosition ) );
}
}
}

// Example usage of the collected words:
for ( const range of wordRanges ) {
const fragment = model.getSelectedContent( model.createSelection( range ) );
const html = editor.data.stringify( fragment );

console.log( `[${ range.start.path }] - [${ range.end.path }]`, html );
}
```

### How to listen on a double click (e.g. link elements)?

```js
Expand Down

0 comments on commit e55e955

Please sign in to comment.