Xth pozitsiyasi intervallarida (javascript) muntazam ifoda yordamida mag'lubiyatni almashtirish

I would very much appreciate some assistance from the community on replacing a string at xth position intervals, using JavaScript regex. For example, if the string length is 161 and the replacement text is
, regex would replace the string at the 40th, 80th, 120th, and 160th positions with this replacement text. Is this possible using regex?

Katta rahmat.

2
Ha, bu to'g'ri. Nima uchun boshqa texnika emas? Chunki mening fikrimcha, regex kodi kamroq kodlarni talab qiladi va eng oddiy bo'lishi mumkin. Biroq men boshqa usullarga ochiqman.
qo'shib qo'ydi muallif user717236, manba
Ha, rahmat, maslahatingiz uchun minnatdorman. Eslatma: Shu sababli yuqoridagi izohimda "istaymiz" va "xohlamasligimni" aytdim.
qo'shib qo'ydi muallif user717236, manba
Regex bilan mumkin bo'lsa-da, buni amalga oshirish uchun boshqa usullardan foydalanmang. Menimcha, siz har bir narsani (n% 40 == 0) joylashtirishni xohlaysiz.
qo'shib qo'ydi muallif FailedDev, manba
Kodning kamroq satrlari, uni oddiy yoki samaraliroq qilmaydi. Qayd qilish kerak bo'lgan bir narsa.
qo'shib qo'ydi muallif FailedDev, manba

2 javoblar

A method to add
at ever 40th position is by using the following line:

string = string.replace(/([\S\s]{40})/g , "$1
");

Agar siz manzilni dinamik ravishda ishlatmoqchi bo'lsangiz:

var positions = 40;
var pattern = new RegExp("([\\s\\s]{" + positions + "})", "g");
string = string.replace(pattern , "$1
");

Explanation of the code:

  1. The first argument of the replace function is a RegExp:
    • ([\S\s] = all non-whitespace and white-space characters = every character).
    • {40} = 40 characters
    • The g flag means: global match, ie: match every possible occurence
    • The parentheses inside the RegExp means: Create a group. This group can later be referred by $1 (first group)
  2. The second argument of the replace function contains $1
    . That is: replace the full match by the first group ($1), and add
    to it.
4
qo'shib qo'ydi
Sizning yordamingiz uchun sizga katta rahmat. Bu eng yuqori baholanadi.
qo'shib qo'ydi muallif user717236, manba
var str = "12345678901234567890";
var newStr = str.replace(/(.{5})/g,"$1
");

har 40 uchun 5 dan 40 gacha o'zgaring.

1
qo'shib qo'ydi
Katta rahmat. Bu echimni ham yaxshi ko'raman. Yana bir bor rahmat.
qo'shib qo'ydi muallif user717236, manba
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb