¿Cómo eliminar texto de una string en JavaScript?

Hay tres métodos para eliminar el texto de una string que se enumeran a continuación:

Método 1: Uso del método replace() : el método replace se puede usar para reemplazar la string especificada con otra string. Toma dos parámetros, primero es la string que se reemplazará y el segundo es la string que se reemplaza desde la primera string. A la segunda string se le puede dar una string vacía para que se elimine el texto que se va a reemplazar. Sin embargo, este método solo elimina la primera aparición de la string.

Sintaxis:

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

Ejemplo: este ejemplo reemplaza la primera aparición de string.

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to remove text from
        a string in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to remove text from a
        string in JavaScript?
    </b>
      
    <p>Original string is GeeksforGeeks</p>
      
    <p>
        New String is: <span class="output"></span>
    </p>
  
    <button onclick="removeText()">
        Remove Text
    </button>
      
    <script type="text/javascript">
        function removeText() {
            originalText = 'GeeksForGeeks';
            newText = originalText.replace('Geeks', '');
  
            document.querySelector('.output').textContent
                    = newText;
        }
    </script>
</body>
</html>                    

Producción:

  • Antes de hacer clic en el botón:
    replace-before
  • Después de hacer clic en el botón:
    replace-after

Método 2: usar el método replace() con expresiones regulares: este método se usa para eliminar todas las ocurrencias de la string especificada, a diferencia del método anterior. Se usa una expresión regular en lugar de la string junto con la propiedad global. Esto seleccionará todas las ocurrencias en la string y se puede eliminar usando una string vacía en el segundo parámetro.

Sintaxis:

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

Ejemplo:

<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to remove text from a
        string in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to remove text from a 
        string in JavaScript?
    </b>
      
    <p>Original string is GeeksforGeeks</p>
      
    <p>
        New String is: <span class="output"></span>
    </p>
  
    <button onclick="removeText()">
        Remove Text
    </button>
      
    <script type="text/javascript">
        function removeText() {
            originalText = 'GeeksForGeeks';
            newText = originalText.replace(/Geeks/g, '');
  
            document.querySelector('.output').textContent
                    = newText;
        }
    </script>
</body>
</html>                    

Producción:

  • Antes de hacer clic en el botón:
    replace-global-before
  • Después de hacer clic en el botón:
    replace-global-after

Método 3: Usar el método substr(): El método substr() se usa para extraer partes de una string entre los parámetros dados. Este método toma dos parámetros, uno es el índice de inicio y el otro es la longitud de la string que se seleccionará de ese índice. Al especificar la longitud requerida de la string necesaria, la otra parte se puede descartar. Esto se puede usar para eliminar prefijos o sufijos en una string.

Sintaxis:

string.substr(start, length);

Ejemplo:

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to remove text from a
        string in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to remove text from a
        string in JavaScript?
    </b>
      
    <p>Original string is GeeksforGeeks</p>
      
    <p>
        New String is: <span class="output"></span>
    </p>
  
    <button onclick="removeText()">
        Remove Text
    </button>
      
    <script type="text/javascript">
        function removeText() {
            originalText = 'GeeksForGeeks';
            newText = originalText.substr(3, 9);
  
            document.querySelector('.output').textContent
                    = newText;
        }
    </script>
</body>
  
</html>                    

Producción:

  • Antes de hacer clic en el botón:
    substr-before
  • Después de hacer clic en el botón:
    substr-after

Publicación traducida automáticamente

Artículo escrito por sayantanm19 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *