Перенос абзаца с тегом span на 4 буквы

Мне нужно обернуть весь текст тегом span через каждые 4 буквы. я могу разделить и присоединиться. но я не смог точно обернуть 4 буквы. кто-нибудь помочь мне, пожалуйста? в настоящее время это принимает другой счет.

const str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

const joined = str.split(' ').join('');

const reg = new RegExp(/(\w+)/, 'g');

const value = joined.replace(reg, '<span>$1</span>');

console.info(value)

Вы имеете в виду <span>Lore</span><span>mIps</span><span>umis</span>... ?

kyun 22.02.2023 06:22

@kyun да, точно

3gwebtrain 22.02.2023 06:28

Почему по этому вопросу проголосовали против?

3gwebtrain 22.02.2023 06:46
Как собрать/развернуть часть вашего приложения Angular
Как собрать/развернуть часть вашего приложения Angular
Вам когда-нибудь требовалось собрать/развернуть только часть вашего приложения Angular или, возможно, скрыть некоторые маршруты в определенных средах?
Оптимизация React Context шаг за шагом в 4 примерах
Оптимизация React Context шаг за шагом в 4 примерах
При использовании компонентов React в сочетании с Context вы можете оптимизировать рендеринг, обернув ваш компонент React в React.memo сразу после...
Интервьюер: Почему &apos;[] instanceof Object&apos; возвращает &quot;true&quot;?
Интервьюер: Почему '[] instanceof Object' возвращает "true"?
Все мы знаем, что [] instanceof Array возвращает true, но почему [] instanceof Object тоже возвращает true?
Абстрактное синтаксическое дерево (AST) и как оно работает с ReactJS
Абстрактное синтаксическое дерево (AST) и как оно работает с ReactJS
Абстрактное синтаксическое дерево (AST) - это древовидная структура данных, которая представляет структуру и иерархию исходного кода на языке...
3
3
50
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Вот подход

const str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

const chunks = str.replace(/\s+/g, '').match(/.{1,4}/g);; 
const wrapped = chunks.map((chunk) => `<span>${chunk}</span>`).join("");

console.info(wrapped);

Но я обнаружил, что он включает «пробелы», мне не нужно подсчитывать пробелы.

3gwebtrain 22.02.2023 06:32

Обновил ответ, удалив пробелы перед преобразованием в фрагменты из 4 символов.

Abito Prakash 22.02.2023 06:34

Принятый ответ включает «пробелы» @3gwebtrain

Abito Prakash 23.02.2023 06:19
Ответ принят как подходящий

Вы можете использовать match(), чтобы разделить строку на массив подстрок по 4 буквы в каждой, после этого используйте метод map(), чтобы обернуть каждую подстроку тегом span.

const str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

const substrings = str.match(/.{1,4}/g); // split the string into substrings containing four letters

const wrapped = substrings.map(substring => `<span>${substring}</span>`).join(''); // wrap each substring with a span tag and join the resulting array of strings

console.info(wrapped);

Для меня это работает нормально:

const str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

    const joined = str.split(' ').join('');
    
    const reg = new RegExp(/(.{4})/, 'g');
    
    const value = joined.replace(reg, '<span>$1</span>');
    
    console.info(value)

Другие вопросы по теме