How to change the selected Template using javascript?

You are already using the correct action, i.e. wp.data.dispatch( 'core/editor' ).editPost(), however, you should instead change the property named template. I.e.

wp.data.dispatch( 'core/editor' ).editPost( { template: 'article.php' } )

Also, for completeness, here’s a sample implementation based on what you’re trying to do:

const { subscribe, select, dispatch } = wp.data;

// The text you want to find.
const TEXT_TO_FIND = 'foo';

// The template you want to change to when the above text is found.
const TEMPLATE_SLUG = 'article.php';

let previousTemplateSlug = '';

const unsubscribe = subscribe( () => {
    const postContent  = select( 'core/editor' ).getEditedPostContent();
    const templateSlug = select( 'core/editor' ).getEditedPostAttribute( 'template' );

    // Build the regular expression pattern for searching the text.
    const RE = new RegExp( '\\b' + TEXT_TO_FIND + '\\b' );

    if ( ( TEMPLATE_SLUG !== templateSlug ) &&
        postContent && RE.test( postContent )
    ) {
        dispatch( 'core/editor' ).editPost( { template: TEMPLATE_SLUG } );
        previousTemplateSlug = templateSlug;
    } else if ( previousTemplateSlug && ! RE.test( postContent ) ) {
        // Revert to the previous template.
        dispatch( 'core/editor' ).editPost( { template: previousTemplateSlug } );
        previousTemplateSlug = '';
    }
} );