const
text = 'Sport',
str = 'port';
console.log(text.replace(new RegExp(`(${str})`, 'g'), '#$1#'));или есть что-то оптимальней ?
text.replace(str, `#${str}#`). Правда, в отличие от регулярки - множественную замену так сделать не получится.
const caesar = (str, offset) => Array
.from(str, n => String.fromCharCode(n.charCodeAt(0) + offset))
.join('');
const caesarTemplate = (title, offset) => `
<div class="caesar">
<textarea class="caesar-input" data-offset="${offset}"></textarea>
<hr>
<p>${title}: <span class="caesar-output"></span></p>
</div>
`;
document.addEventListener('input', ({ target: t }) => {
if (t.matches('.caesar-input')) {
const output = t.closest('.caesar').querySelector('.caesar-output');
output.innerHTML = caesar(t.value, +t.dataset.offset);
}
});
document.body.insertAdjacentHTML('beforeend', [
[ 'Шифр', 3 ],
[ 'Расшифровка', -3 ],
].map(n => caesarTemplate(...n)).join(''));
const text = (el => (el.innerHTML = html, el.innerText))(document.createElement('div'));const text = new DOMParser().parseFromString(html, 'text/html').body.textContent;const fragment = document.createRange().createContextualFragment(html);
const iter = document.createNodeIterator(fragment, NodeFilter.SHOW_TEXT);
const texts = [];
for (let n; n = iter.nextNode(); texts.push(n.nodeValue)) ;
<span class="prev" data-step="-1">Prev</span>
<span class="next" data-step="+1">Next</span>eq позволяет указывать отрицательные индексы, которые используются для отсчёта позиции элемента начиная с конца; в случае чистого js надо будет добавить к сумме количество элементов, чтобы потенциальное отрицательное значение стало положительным, и при этом не изменился остаток от деления.const itemSelector = 'li';
const buttonSelector = '[data-step]';
const activeClass = 'active';$(buttonSelector).click(function() {
const { step } = this.dataset;
const $items = $(itemSelector);
const $active = $items.filter(`.${activeClass}`);
$active.removeClass(activeClass);
$items.eq(($active.index() + +step) % $items.length).addClass(activeClass);
});
// или
const items = document.querySelectorAll(itemSelector);
let index = 0;
document.querySelectorAll(buttonSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick({ currentTarget: { dataset: { step } } }) {
items[index].classList.remove(activeClass);
index = (index + items.length + +step) % items.length;
items[index].classList.add(activeClass);
}
Math.min или перебираем вручную и сравниваем):const minDigit = num =>
Number.isFinite(num)
? Math.min(...`${num}`.replace(/\D/g, ''))
: null;
// или
const minDigit = num =>
(String(num).match(/\d/g) || []).reduce((min, n) => {
return min === null || n < min ? +n : min;
}, null);minDigit(1) // 1
minDigit(759486394) // 3
minDigit(-56.209) // 0
minDigit(Infinity) // null
minDigit(NaN) // null
minDigit('hello, world!!') // null
li на его же текст:$('.breadcrumb').children().last().text((i, text) => text);
// или
document.querySelector('.breadcrumb').lastElementChild.innerText += '';a есть элементы, они не будут удалены):$('.breadcrumb > :last > *').replaceWith((i, html) => html);
// или
(el => el.replaceWith(...el.childNodes))
(document.querySelector('.breadcrumb > :last-child > *'));
const containerSelector = 'ul';
const buttonSelector = 'a';
const elementSelector = '.drop';const $el = $(elementSelector);
$(containerSelector).on('click', buttonSelector, function(e) {
$(e.currentTarget).after($el);
// или
$(this).parent().append($el);
// или
$el.insertAfter(this);
});const el = document.querySelector(elementSelector);
document.querySelector(containerSelector).addEventListener('click', ({ target: t }) => {
if (t = t.closest(buttonSelector)) {
t.after(el);
// или
t.insertAdjacentElement('afterend', el);
// или
t.parentNode.insertBefore(el, t.nextSibling);
// или
t.parentNode.append(el);
// или
t.parentNode.appendChild(el);
}
});
words.replace(index, 1, word.charAt(0));replace у массивов нет. Есть splice.как реализовали бы данную задачу вы?
const newWords = words.flatMap(RegExp.prototype.exec.bind(/.{0,1}/));
// или
const newWords = [];
for (const n of words) {
newWords.push(n[0] || '');
}
// или
const newWords = (function get(i, n = words[i]) {
return n != null ? [ n.slice(0, 1), ...get(-~i) ] : [];
})(0);words.forEach(([ n = '' ], i, a) => a[i] = n);
// или
words.splice(0, words.length, ...words.map(n => n.charAt()));
// или
for (let i = 0; i < words.length; i++) {
words[i] = words[i].replace(/(?<=.).+/, '');
}
const $form = $('.order__form-contacts').on('change', '[name="legal-status"]', e => {
$form.find('.order__form-file')[e.target.value === '2' ? 'slideDown' : 'slideUp']();
});
arr1.forEach(function({ id }) {
if (this[id]) {
this[id].isAdded = true;
}
}, arr2.reduce((acc, n) => (acc[n.id] = n, acc), {}));const newArr2 = arr2.map(function({ ...n }) {
if (this.has(n.id)) {
n.isAdded = true;
}
return n;
}, new Set(arr1.map(n => n.id)));
const text = 'определённый текст';
const link = document.querySelector(`a[href*="${text}"]`);
if (link) {
link.click();
}
.click() на [0].click() или .get(0).click().
const $filters = $('.filter').change(function() {
const filters = $filters
.get()
.filter(n => n.value)
.map(n => [ n.dataset.name, n.value ]);
$('.product')
.hide()
.filter((_, el) => filters.every(n => el.dataset[n[0]] === n[1]))
.show();
});
.modal-wrapper .open { должно быть .modal-wrapper.open {.
blur, а не focustoUpperCase не у строки, а у массива - забыто [0]input.addEventListener('blur', function() {
const value = this.value.trim();
if (value) {
this.value = value
.split(/\s+/)
.map(n => n[0].toUpperCase() + n.slice(1))
.join(' ');
}
});
// или
input.addEventListener('blur', ({ target: t }) => {
t.value = t.value
.trim()
.replace(/\s+/g, ' ')
.replace(/(^|\s)\S/g, m => m.toUpperCase());
});
const getPrimitiveProps = (obj) =>
Object.entries(obj).reduce((acc, [ k, v ]) => ({
...acc,
...(v instanceof Object ? getPrimitiveProps(v) : { [k]: v }),
}), {});const getPrimitiveProps = (obj) =>
Object.assign({}, ...Object.entries(obj).map(([ k, v ]) =>
v instanceof Object ? getPrimitiveProps(v) : { [k]: v }
));
document.addEventListener('keydown', e => {
if (e.key === 'Backspace' && e.target !== display) {
display.value = display.value.slice(0, -1);
// или
display.value = display.value.substring(0, display.value.length - 1);
// или
display.value = display.value.replace(/.$/, '');
// или
display.value = display.value.match(/.*(?=.$)/);
// или
display.value = [...display.value].filter((n, i, a) => -~i < a.length).join('');
}
});