从一个字符串中获取几个子字符串作为数组返回

时间:2019-10-25 03:23:36

标签: javascript reactjs typescript

所以我有这个字符串:

<li class="list-group-item">
          <a href=https://en.wikipedia.org/wiki/C target="_blank">
            <h4>C</h4>
          </a>
          <p>C or c is the third letter in the English alphabet and a letter of the alphabets of many other writing systems which inherited it from the Latin alphabet.</p>
        </li>

        <li class="list-group-item">
          <a href=https://en.wikipedia.org/wiki/Copyright_infringement target="_blank">
            <h4>Copyright infringement</h4>
          </a>
          <p>Copyright infringement (colloquially referred to as piracy) is the use of works protected by copyright law without permission for a usage where such permission is required, thereby infringing certain exclusive rights granted to the copyright holder, such as the right to reproduce, distribute, display or perform the protected work, or to make derivative works.</p>
        </li>

        <li class="list-group-item">
          <a href=https://en.wikipedia.org/wiki/Copyright_law_of_the_United_States target="_blank">
            <h4>Copyright law of the United States</h4>
          </a>
          <p>The copyright law of the United States is intended to encourage the creation of art and culture by rewarding authors and artists with a set of exclusive rights.</p>
        </li>

我想替换'href =“'和下一个空格''之间的所有子字符串。 目标是更改另一个链接。

我使用的功能是:

const findSubstrings = function (json: string) {
    const subStrings = json.substring(
        json.indexOf("href=") + 1, 
        json.indexOf(" ")
    );
}

问题在于它仅返回一个值,我想将所有链接作为字符串返回数组中。我想我可以将大字符串拆分为较小的子字符串,而不是拆分为较小的子字符串,但感觉有点过分。有没有更简单的方法可以解决?

1 个答案:

答案 0 :(得分:0)

尝试一下:

str = str.replace(/href=\S+/g, (oldLink) => {
    console.log(oldLink);
    const newLink = "https://www";
    return "href=" + newLink;
});