๐ฐreplacer function
JS โฉ value โฉ primitive โฉ String โฉ method โฉ .replace() โฉ replacer function
๐็ฏไพ๏ผ
minus one - replacer function example.
codepen โฉ str.replace()
// p1: nondigits
// p2: digits
// p3: non-alphanumerics
let regex = /([^\d]+)(\d+)([^\w]+)/;
// groups: โฐโ p1 โโฏโฐp2โโฏโฐโ p3 โโฏ
// offset โด
// 012345678901234567
let str = '000abc12345#$*%xxx';
// โฐโโฏโฐ1โฏโฐโ2โโฏโฐ3โโฏโฐโโฏ
// $`โฐโ match โโโฏ $'
// โญ๏ธ replacement: (replacer function)
let str2 = str.replace(regex, (
match, // matched substring = $&
p1, p2, p3, // capture groups = $1, $2, $3 ...
offset, // offset (index) of matched substring
string, // whole string
groups // "named" capturing groups (object)
) => {
// 3 โด undefined โด
log(match, p1, p2, p3, offset, string, groups);
return '--' + ([p1, p2, p3].join('-')) + '--';
});
// str.replace() โญโโโ replaced โโโโฎ
log(str2); // "000--abc-12345-#$*%--xxx"
// โญ๏ธ ๆณจๆ๏ผไธๅปๅ็้จๅๆๅๅฐไธๅ็ไธไพ๏ผ โฐโญ๏ธโฏ โฐโญ๏ธโฏ
// camel case to kebab case
let kebab = 'borderTop'.replace(/[A-Z]/g, (match, offset) =>
(offset > 0 ? '-' : '') + match.toLowerCase()
);
log(kebab); // "border-top"
๐็ฏไพ๏ผ
// replace function
"the cia and fbi".replace(/\b(fbi|cia)\b/g,
match => match.toUpperCase() // โ the CIA and FBI
)
ๅ ็บ str.replace() ๆๅฐๆฏๅ match ้ฒ่กๆๅฎ็ replacer function ๆไฝ๏ผๆไปฅๅฆๆๆๅๅชๆฏ่ฆๅฐๆฏๅ match ๅๆไบๅไฝ๏ผไฝไธๅจไนไปฃๆๅพ็ๆๅญ๏ผๅณๅฏไฝฟ็จๆญคๆนๆณใๆๅๅฏไปฅๆ้็จฎๅๆณ็ถไฝๆฏ๏ผstr.match().forEach() ็ๆทๅพ๏ผไฝๅๆฒๆ str.match().forEach() ็็ผบ้ป๏ผๅ ็บๆฒๆ match ๆ๏ผstr.replace() ้ ๅคๅฐฑๆฏไธ้ฒ่กๆฟๆ่ๅทฒ๏ผไธฆไธๆ็ข็้ฏ่ชค่จๆฏใ
็ถ str.match() ๆฒๆ็ตๆๆ๏ผๆๅๅณ null๏ผ้ๆๅฆๆๅผๅซ .forEach() ๆๅบ็พๅ้กโ๏ธ
codewars โฉ most frequently used words in text โญ๏ธ
encodeURI() โญ๏ธ
String โฉ
.replace() โฉ
Last updated