I made some tweaks to your code. Thanks for the nice snippet!
These changes limit the characters in the filename, save in the default note folder, link to the actual basename (in case of existing file) and doesn’t delete the text but rather leaves it as a selection so you can choose to delete it yourself.
!function() {
async function extractSelection() {
const doc = app.workspace.activeLeaf.view.sourceMode.cmEditor.doc
const selectedText = doc.getSelection()
if (!selectedText) { return }
const [header, ...contentArr] = selectedText.split('\n')
const reAlphanum = /[^\w\s_-]+/g
const rootFolder = app.fileManager.getNewFileParent()
const title = header.replace(reAlphanum, '').substring(0, 252)
const file = await app.fileManager.createNewMarkdownFile(rootFolder, title)
var selHead = doc.getCursor("anchor")
var selEnd = doc.getCursor("end")
app.vault.modify(file, header + contentArr.join('\n'))
doc.replaceSelection('[[' + file.basename + ']]\n' + selectedText)
selHead.line = selHead.line + 1
selEnd.line = selEnd.line + 1
doc.setSelection(selHead, selEnd)
}
app.commands.addCommand({
id: 'app:extract-selection',
name: 'Extract selection',
callback: extractSelection,
hotkeys: []
})
}()