cut out part of a string

前端 未结 8 1559
北荒
北荒 2021-02-18 16:17

Say, I have a string

\"hello is it me you\'re looking for\"

I want to cut part of this string out and return the new string, something like

8条回答
  •  野的像风
    2021-02-18 17:07

    Some other more modern alternatives are:

    1. Split and join

      function cutFromString(oldStr, fullStr) {
        return fullStr.split(oldStr).join('');
      }
      cutFromString('there ', 'Hello there world!'); // "Hello world!"
      

      Adapted from MDN example

    2. String.replace(), which uses regex. This means it can be more flexible with case sensitivity.

      function cutFromString(oldStrRegex, fullStr) {
        return fullStr.replace(oldStrRegex, '');
      }
      cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
      

提交回复
热议问题