Перенос абзаца с тегом 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
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
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)

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