Skip to content

Commit 8bdd9c9

Browse files
committed
predefine regular expressions in JavaScript functions
1 parent 0f447d6 commit 8bdd9c9

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/js/06-copy-to-clipboard.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
;(function () {
22
'use strict'
3+
4+
var CMD_RX = /^\$ (\S[^\\\n]*(\\\n(?!\$ )[^\\\n]*)*)(?=\n|$)/gm
5+
var LINE_CONTINUATION_RX = /( ) *\\\n *|\\\n( ?) */g
6+
var TRAILING_SPACE_RX = / +$/gm
7+
38
;[].slice.call(document.querySelectorAll('.doc pre.highlight, .doc .literalblock pre')).forEach(function (pre) {
49
var code, language, lang, copy, toast, toolbox
510
if (pre.classList.contains('highlight')) {
@@ -43,16 +48,14 @@
4348
})
4449

4550
function extractCommands (text) {
46-
var cmdRx = /^\$ (\S[^\\\n]*(\\\n(?!\$ )[^\\\n]*)*)(?=\n|$)/gm
47-
var cleanupRx = /( ) *\\\n *|\\\n( ?) */g
4851
var cmds = []
4952
var m
50-
while ((m = cmdRx.exec(text))) cmds.push(m[1].replace(cleanupRx, '$1$2'))
53+
while ((m = CMD_RX.exec(text))) cmds.push(m[1].replace(LINE_CONTINUATION_RX, '$1$2'))
5154
return cmds.join(' && ')
5255
}
5356

5457
function writeToClipboard (code) {
55-
var text = code.innerText.replace(/ *$/gm, '')
58+
var text = code.innerText.replace(TRAILING_SPACE_RX, '')
5659
if (code.dataset.lang === 'console' && text.startsWith('$ ')) text = extractCommands(text)
5760
window.navigator.clipboard.writeText(text).then(
5861
function () {

0 commit comments

Comments
 (0)