Topic on Talk:VisualEditor

Get wikitext using JavaScript

6
BrandonXLF (talkcontribs)

Is there a way to get the current wikitext being shown in the editor using JavaScript?

Whatamidoing (WMF) (talkcontribs)

Why do you want to do that? I'm pretty sure that there's a much easier way to accomplish your goal.

BrandonXLF (talkcontribs)

For a user script that will run some regex replacements on the code in the editor.

ESanders (WMF) (talkcontribs)

I assume you are talking about 2017WTE, in which case the surface is in fact compatible with the textSelection API, so

$( '#wpTextbox1' ).textSelection( 'getContents' )

would work. You can use the same API to replace the contents with setContents.

Note this isn't the most efficient API as the whole document will be replaced. If you want to do more targeted replacements you can use the document's findText method. Here's an example script that fixes date formats:

var target = ve.init.target,
	surface = target.surface.model,
	// non-global regex for returning matches
	pattern = new RegExp( '([0-9]{1,2})/([0-9]{1,2})(?:/([0-9]{1,4}))?' );

target.initialEditSummary = 'Fix date formats.';

surface.documentModel.findText( new RegExp( pattern.source, 'g' ), { noOverlaps: true } ).map( function ( range ) {
	// Build all fragments before modifying
	return surface.getLinearFragment( range );
} ).forEach( function ( fragment ) {
	var matches = fragment.getText().match( pattern ),
		year = matches[ 3 ] ? +matches[ 3 ] : new Date().getFullYear();
	if ( year < 100 ) {
		year += 2000;
	}
	// Sanity check that numbers are in range. Avoids matching things like 24/7.
	if ( +matches[ 1 ] > 12 || +matches[ 2 ] > 31 ) {
		return;
	}
	fragment.insertContent( year + '-' + matches[ 1 ].padStart( 2, '0' ) + '-' + matches[ 2 ].padStart( 2, '0' ), true );
} );
Whatamidoing (WMF) (talkcontribs)

Is this complicated enough that you really need to use a script? VisualEditor (visual and wikitext modes) has a built-in find/replace module that handles regex.

BrandonXLF (talkcontribs)

I'm sure there's a better way to do it, but with the regex I'm using, I have to split the text into arrays and run several different regex rules on the text.

Reply to "Get wikitext using JavaScript"