JavaScript 如何从字符串中删除文本

JavaScript 如何从字符串中删除文本

在本文中,我们将学习如何从JavaScript字符串中删除文本。有以下三种方法可以从字符串中删除文本:

从字符串中删除文本的方法

  • 使用replace()方法
  • 使用带有正则表达式的replace()方法
  • 使用substr()方法
  • 使用replaceAll()方法

方法1:使用replace()方法

replace()方法用于将指定的字符串替换为另一个字符串。它接受两个参数,第一个参数是要替换的字符串,第二个参数是从第一个字符串中被替换的字符串。第二个字符串可以为空字符串,这样就可以删除要替换的文本。但是该方法只会删除第一个出现的字符串。

语法:

string.replace('textToReplace', '');  

示例:

这个示例替换了字符串的第一个出现。

// Function to remove text
function removeText() {
    // Input string
    let originalText = 'GeeksForGeeks';
    // Replace method to remove given text
    let newText = originalText.replace('Geeks', '');
     
    // Display output
    console.log(newText);
}
 
// Function call
removeText();

输出

ForGeeks

方法2:使用replace()方法和正则表达式

这种方法用于删除指定的字符串的所有出现,与前一种方法不同。使用正则表达式和全局属性来代替字符串。这将选择字符串中的每个出现,并可以通过在第二个参数中使用空字符串来删除。

语法:

string.replace(/regExp/g, '');  

示例: 此示例使用上述方法在JavaScript中替换字符串中的文本。

function removeText() {
     
    // Input string
    let originalText = 'GeeksForGeeks';
     
    // Replace method with regEx
    let newText = originalText.replace(/Geeks/g, '');
     
    // Display output
    console.log(newText);
}
 
// Function call
removeText();

输出

For

方法3:使用substr()方法

substr()方法用于提取字符串中给定参数之间的部分。该方法需要两个参数,一个是起始索引,另一个是从该索引中选择的字符串的长度。通过指定所需的字符串长度,可以丢弃其他部分。这可以用于删除字符串中的前缀或后缀。

语法:

string.substr(start, length);  

示例: 这个示例使用上述方法在JavaScript中替换字符串中的文本。

// Function to remove text
function removeText() {
    // Input string
    let originalText = 'GeeksForGeeks';
     
    // Using substr with index range to remove text
    let newText = originalText.substr(3, 9);
 
    // Display text
    console.log(newText);
}
 
// Function call
removeText();

输出

ksForGeek

方法4:使用 replaceAll() 方法

示例: 在本文中,我们将使用 JavaScript 的 replaceAll() 方法从输入字符串中删除所有出现的指定文本。

// Function to remove text
function removeText() {
    // Input string
    let originalText = 'GeeksForGeeks';
     
    // Implementing replaceAll with text to be removed
    let newText = originalText.replaceAll('Geeks', '');
     
    // Display output
    console.log(newText);
}
 
// Function call
removeText();

输出

For

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程