Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

you are a javascript master, prove some ways to remove string from string, shorter as…

  1. User

    you are a javascript master, prove some ways to remove string from string, shorter as possible

  2. Assistant
    1. Using replace method:

    let str = "hello world"; str = str.replace("world", "");

    1. Using slice method:

    let str = "hello world"; str = str.slice(0, 5) + str.slice(11);

    1. Using substr or substring method:

    let str = "hello world"; str = str.substr(0, 5) + str.substr(11);

    or

    let str = "hello world"; str = str.substring(0, 5) + str.substring(11);

    1. Using regular expressions:

    let str = "hello world"; str = str.replace(/world/, "");

    1. Using split and join methods:

    let str = "hello world"; let arr = str.split("world"); str = arr.join("");

  3. User

    any other way?

  4. Assistant

    Yes, here are two more ways:

    1. Using the splice method to change the string into an array and remove the element:

    let str = "hello world"; let arr = str.split(""); arr.splice(6,5); str = arr.join("");

    1. Using the substr method with negative indices to remove the last part of the string:

    let str = "hello world"; str = str.substr(0, str.length-5);