๐str.replace()
Last updated
Last updated
JS โฉ value โฉ primitive โฉ String โฉ method โฉ .replace()
// quoting style: single (') -> double (")
let text = "'I'm the cook,' he said, 'it's my job.'";
text.replace(/(^|\W)'|'(\W|$)/g, '$1"$2'));
// โฐโ1โโโฏ โฐโ2โโโฏ
// โญ๏ธ Groups that are not matched will be replaced by nothing.
// โ "I'm the cook," he said, "it's my job."
๐็ฏไพ๏ผ
minus one - replacer function example.
codepen โฉ str.replace()
// โญ๏ธ replacement string
// replacement string โด
// โญ1โโฎ โญโ2โโฎ โญ 1 โฎ โญ 2 โฎ โญโโโโโโโฎ
let str1 = 'John Smith'.replace(/(\w+)\s(\w+)/, '$2, $1');
// โฐ match โโฏ โญโ2โโฎ โญ1โโฎ
log(str1); // "Smith, John"
// 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"
ๅ ็บ 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() โฉ