Bạn có thể thay đổi chuỗi trong javascript không?

Để thay thế tất cả các lần xuất hiện của

str.replace(pattern, replacement)
3, bạn cần sử dụng biểu thức chính quy với khóa chuyển đổi
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
0 (tìm kiếm toàn cầu). Ví dụ:
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
1 thay vì
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
2

const text = "Java is awesome. Java is fun."

// notice the g switch in the regex pattern

const pattern = /Java/g; const new_text = text.replace(pattern, "JavaScript");

console.log(new_text);

đầu ra

JavaScript is awesome. JavaScript is fun.

Ở đây, phương thức

str.replace(pattern, replacement)
0 thay thế cả hai lần xuất hiện của
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
4 bằng
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
5


Thay thế mà không xem xét chữ hoa/chữ thường

Phương thức

str.replace(pattern, replacement)
0 phân biệt chữ hoa chữ thường. Để thực hiện thay thế không phân biệt chữ hoa chữ thường, bạn cần sử dụng biểu thức chính quy với công tắc
const text = "Java is awesome. Java is fun."

// passing a string as the first parameter

let pattern = "Java"; let new_text = text.replace(pattern, "JavaScript");

console.log(new_text); // passing a regex as the first parameter

pattern = /Java/; new_text = text.replace(pattern, "JavaScript");

console.log(new_text);
7 (tìm kiếm không phân biệt chữ hoa chữ thường)

ví dụ 3. Thay thế không phân biệt chữ hoa chữ thường

const text = "javaSCRIPT JavaScript"

// the first occurrence of javascript is replaced
let pattern = /javascript/i;  // case-insensitive search
let new_text = text.replace(pattern, "JS");
console.log(new_text)  // JS JavaScript

// all occurrences of javascript is replaced
pattern = /javascript/gi;  // case-insensitive and global search
new_text = text.replace(pattern, "JS");
console.log(new_text)  // JS JS

đầu ra

JS JavaScript
JS JS

Ví dụ 4. Vượt qua chức năng như một sự thay thế

Bạn cũng có thể truyền một hàm (thay vì một chuỗi) làm tham số thứ hai cho phương thức

str.replace(pattern, replacement)
0

const text = "Random digit: 3"

// generate a random digit between 0 and 9
function generateRandomDigit() {
  return Math.floor(Math.random() * 10)
}

// regex to match a digit

const pattern = /\d/; const new_text = text.replace(pattern, generateRandomDigit);

console.log(new_text)

đầu ra

Random digit: 8

Bạn có thể nhận được đầu ra khác nhau khi chạy chương trình này. Đó là do chữ số đầu tiên trong văn bản được thay thế bằng một chữ số ngẫu nhiên trong khoảng từ 0 đến 9

Phương thức String.prototype.replace() tìm kiếm lần xuất hiện đầu tiên của một chuỗi và thay thế nó bằng chuỗi đã chỉ định. Nó làm điều này mà không làm thay đổi chuỗi gốc

Phương pháp này cũng hoạt động với các biểu thức chính quy, vì vậy mục bạn đang tìm kiếm có thể được biểu thị dưới dạng biểu thức chính quy

Giá trị trả về dưới dạng giá trị được thay thế có thể được biểu thị dưới dạng chuỗi hoặc hàm

Cú pháp cơ bản của chuỗi. nguyên mẫu. Phương thức thay thế ()

const variable = variable.replace("stringToReplace", "expectedString");

Bạn sử dụng phương pháp replace() bởi

  • gán chuỗi hoặc chuỗi ban đầu cho một biến
  • khai báo một biến khác
  • đối với giá trị của biến mới, thêm trước tên biến mới bằng phương thức thay thế ()
  • Dấu phẩy phân tách chuỗi bạn muốn thay thế và chuỗi dự kiến ​​trong ngoặc

Ví dụ về chuỗi. nguyên mẫu. Phương thức thay thế ()

Một ví dụ cơ bản sẽ như thế này

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp

Trong ví dụ trên

  • Tôi đã khai báo một biến có tên là mã hóa và gán cho nó chuỗi “I learned how to code from TV
  • Tôi đã khai báo một biến khác tên là
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    
    0
  • Đối với giá trị của biến
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    
    0, tôi đã đưa vào phương thức replace() và xác định rằng tôi muốn thay thế “TV” từ biến ban đầu bằng “freeCodeCamp”

Dưới đây là một ví dụ chứng minh rằng chuỗi ban đầu không bao giờ bị đột biến (thay đổi) bởi phương thức replace()

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
console.log(coding); // Result: I learned how to code from TV

Trong ví dụ bên dưới, tôi đã sử dụng cụm từ thông dụng để tìm kiếm văn bản khớp với “TV” và thay thế bằng “freeCodeCamp”

const coding = "I learned how to code from TV";
const replacedString = coding.replace(/TV/, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp

Vì phương thức replace() chỉ hoạt động với lần xuất hiện đầu tiên của một số văn bản trong một chuỗi, bạn sẽ làm gì nếu muốn thay thế tất cả các lần xuất hiện của một từ bằng một từ khác trong chuỗi?

Cách Sử dụng Phương pháp const coding = "I learned how to code from TV"; const replacedString = coding.replace("TV", "freeCodeCamp"); console.log(replacedString); // Result: I learned how to code from freeCodeCamp 5

Một phương thức chuỗi hơi giống với phương thức replace() là phương thức

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
5

Phương pháp này thay thế tất cả các lần xuất hiện của một từ nhất định trong một chuỗi

Ví dụ về phương pháp const coding = "I learned how to code from TV"; const replacedString = coding.replace("TV", "freeCodeCamp"); console.log(replacedString); // Result: I learned how to code from freeCodeCamp 5

const coding = "I learned how to code from TV. TV remains in my heart for life.";
const replacedString = coding.replaceAll("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp. freeCodeCamp remains in my heart for life.

Mọi lần xuất hiện của “TV” đã được thay thế bằng “freeCodeCamp” nhờ phương pháp

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
5

Với phương thức ban đầu của replace(), bạn có thể đạt được những gì mà

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
5 thực hiện bằng cách sử dụng các biểu thức chính quy để tìm kiếm mọi lần xuất hiện của một từ nhất định trong một chuỗi và thay thế nó bằng một từ khác

const coding = "I learned how to code from TV. TV remains in my heart for life.";
const replacedString = coding.replace(/TV/g, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp. freeCodeCamp remains in my heart for life.

Tôi có thể tìm kiếm mọi từ khớp với “TV” với cờ

const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
console.log(coding); // Result: I learned how to code from TV
3 của một biểu thức chính quy và thay thế nó bằng “freeCodeCamp”

Cách truyền một hàm cho phương thức replace()

Như tôi đã nói trước đây, bạn có thể biểu thị giá trị bạn muốn trả về dưới dạng giá trị được thay thế dưới dạng hàm

Trong ví dụ bên dưới, tôi đã chuyển đổi tiêu đề của bài viết này thành một URL slug với phương thức thay thế

const articleTitle = "JavaScript Replace – How to Use the String.prototype.replace() Method";
const slugifyArticleTitle = articleTitle.toLowerCase().replace(/ /g, function (article) {
    return article.split(" ").join("-");
  });

console.log(slugifyArticleTitle); //Result: javascript-replace-–-how-to-use-the-string.prototype.replace()-method

Trong kịch bản trên

  • Tôi đã khai báo một biến có tên là
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    console.log(coding); // Result: I learned how to code from TV
    
    5 và đặt tiêu đề cho bài viết này
  • Tôi đã khai báo một biến khác có tên là
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    console.log(coding); // Result: I learned how to code from TV
    
    6 và chuyển đổi tiêu đề của bài viết thành chữ thường bằng phương thức
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    console.log(coding); // Result: I learned how to code from TV
    
    7
  • Tôi đã sử dụng phương thức replace() và tìm kiếm mọi khoảng trắng với
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace("TV", "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    console.log(coding); // Result: I learned how to code from TV
    
    9
  • Sau đó, tôi đã chuyển một hàm cho phương thức replace() và gán cho nó một tham số là
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace(/TV/, "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    
    1. Tham số này dùng để chỉ chuỗi (tiêu đề bài viết) được chuyển thành chữ thường
  • Trong hàm, tôi trả về rằng tôi đang tách tiêu đề bài viết ở bất cứ đâu có khoảng trắng. Điều này đã được thực hiện với phương pháp
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace(/TV/, "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    
    2
  • Sau khi tách tiêu đề bài viết ở mọi nơi có khoảng trắng, tôi đã sử dụng phương pháp
    const coding = "I learned how to code from TV";
    const replacedString = coding.replace(/TV/, "freeCodeCamp");
    
    console.log(replacedString); // Result: I learned how to code from freeCodeCamp
    
    3 để nối các chữ cái riêng lẻ trong chuỗi bằng dấu gạch nối

Phần kết luận

Phương thức String.prototype.replace() là một phương thức chuỗi mạnh mẽ mà bạn có thể hoàn thành rất nhiều việc khi làm việc với các chuỗi trong JavaScript

Ngoài phương pháp String.prototype.replace(), tôi cũng chỉ cho bạn cách sử dụng phương pháp

const coding = "I learned how to code from TV";
const replacedString = coding.replace(/TV/, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
6 – kết hợp của phương pháp String.prototype.replace()

Bạn nên cẩn thận với phương thức

const coding = "I learned how to code from TV";
const replacedString = coding.replace(/TV/, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
6 vì nó chưa được một số trình duyệt hỗ trợ. Thay vì sử dụng
const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
5, tôi cũng đã chỉ cho bạn cách bạn có thể đạt được điều tương tự bằng cách sử dụng biểu thức chính quy để tìm kiếm tất cả các giá trị trong một chuỗi cụ thể

Nếu bạn thấy bài viết này hữu ích, đừng ngần ngại chia sẻ nó với bạn bè và gia đình của bạn

Cảm ơn bạn đã đọc

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO


Bạn có thể thay đổi chuỗi trong javascript không?
Kolade Chris

Nhà phát triển web và nhà văn kỹ thuật tập trung vào các công nghệ giao diện người dùng


Nếu bạn đọc đến đây, hãy tweet cho tác giả để cho họ thấy bạn quan tâm. Tweet một lời cảm ơn

Học cách viết mã miễn phí. Chương trình giảng dạy mã nguồn mở của freeCodeCamp đã giúp hơn 40.000 người có được việc làm với tư cách là nhà phát triển. Bắt đầu

Làm cách nào để thay thế chuỗi trong JavaScript?

Chuỗi. nguyên mẫu. replace() Phương thức replace() trả về một chuỗi mới với một, một số hoặc tất cả các kết quả khớp của một mẫu được thay thế bằng một chuỗi thay thế. Mẫu có thể là một chuỗi hoặc RegExp và sự thay thế có thể là một chuỗi hoặc một hàm được gọi cho mỗi trận đấu.

Chúng ta có thể thay thế chuỗi không?

Chuỗi thay thế(). Phương thức này trả về một chuỗi mới do thay thế tất cả các lần xuất hiện của các ký tự cũ trong chuỗi bằng các ký tự mới .