javascript - 在已知符号之间提取字符串并将其分配为仅使用 javascript 的可重用变量

标签 javascript

我想做什么

  • 我需要从返回的 JSON 值中获取所有 Twitter 用户名,当前在箭头内返回,例如 <jgallardo949>
  • 将这些值分配为变量
  • 将该变量附加到来自 twitter.com 的 url
  • 获取推特用户名前的字符串并将其分配为值
  • 使用其他生成的变量的组合创建一个新变量并将其包装在所需的 HTML 中
  • 在 div 中显示所需的新 HTML
  • 对类为 author 的任何 div 中生成的每个字符串实例执行此操作

示例 JSON

"contributed_by":"Sasha <SashaMasondeCaires>"

期望的 HTML 输出

Sasha <a href="https://www.twitter.com/SashaMasondeCaires">@SashaMasondeCaires</a>

概念解决方案

由于它当前以该格式返回,name <twitter username>那么我想做的就是替换 <<a href="https://www.twitter.com/></a> ,但是我应该如何处理名称,也许将其设为变量,使其类似于

//To get the string inside the <>
var authTw = document.getElementsByClassName("author")[0].innerHTML;
//wrapping solution needs work
var twUsername = "<span>@" + authTw.match(/\<([a-z]*)\>/)[1] + "</span>"
document.getElementsByClassName("author")[0].innerHTML=twUsername;

var authorName = // I need to get the string before the < symbol
var contributorInfo = authorName + '<a href="https://twitter.com/' + twUsername + '">' + twUsername + '</a>';

然后我需要写出结果 contributorInfo在类 .author 的 div 中


当前代码

HTML

<div class="author">{{ beer.contributor }}</div>

JS Babel - Axios

contributor: api.contributed_by,

API 端点

https://api.punkapi.com/v2/beers/random

JSON - 示例

[{
  "id": 126,
  "name": "Jet Black Heart",
  "tagline": "Oatmeal Milk Stout. Dark. Roasty. Velvety.",
  "first_brewed": "01/2016",
  "description": "Good things come to those who wait. This smooth and roasty oatmeal milk stout won our 2015 Prototype Challenge at a canter. Roasty coffee and chocolate lead to a decadent, full-bodied richness of near uncharted depths with a velvet mouthfeel from the addition of oatmeal and a touch of wheat. This is complemented at every turn by the Magnum and Sorachi Ace hops, with the latter bringing an intensity of smooth vanilla and dark berry fruit on the long, rewarding finish.",
  "image_url": "https://images.punkapi.com/v2/126.png",
  "abv": 4.7,
  "ibu": 45,
  "target_fg": 1019,
  "target_og": 1055,
  "ebc": 200,
  "srm": 100,
  "ph": 4.4,
  "attenuation_level": 70,
  "volume": {
    "value": 20,
    "unit": "liters"
  },
  "boil_volume": {
    "value": 25,
    "unit": "liters"
  },
  "method": {
    "mash_temp": [{
      "temp": {
        "value": 65,
        "unit": "celsius"
      },
      "duration": 75
    }],
    "fermentation": {
      "temp": {
        "value": 19,
        "unit": "celsius"
      }
    },
    "twist": null
  },
  "ingredients": {
    "malt": [{
      "name": "Pale Ale",
      "amount": {
        "value": 2.75,
        "unit": "kilograms"
      }
    }, {
      "name": "Wheat",
      "amount": {
        "value": 0.25,
        "unit": "kilograms"
      }
    }, {
      "name": "Dark Crystal",
      "amount": {
        "value": 0.19,
        "unit": "kilograms"
      }
    }, {
      "name": "Brown",
      "amount": {
        "value": 0.38,
        "unit": "kilograms"
      }
    }, {
      "name": "Black",
      "amount": {
        "value": 0.19,
        "unit": "kilograms"
      }
    }, {
      "name": "Carafa Special Malt Type 1",
      "amount": {
        "value": 0.19,
        "unit": "kilograms"
      }
    }, {
      "name": "Flaked Oats",
      "amount": {
        "value": 0.38,
        "unit": "kilograms"
      }
    }, {
      "name": "Crystal 150",
      "amount": {
        "value": 0.25,
        "unit": "kilograms"
      }
    }, {
      "name": "Lactose",
      "amount": {
        "value": 0.38,
        "unit": "kilograms"
      }
    }],
    "hops": [{
      "name": "Magnum",
      "amount": {
        "value": 12.5,
        "unit": "grams"
      },
      "add": "start",
      "attribute": "bitter"
    }, {
      "name": "Sorachi Ace",
      "amount": {
        "value": 6.3,
        "unit": "grams"
      },
      "add": "middle",
      "attribute": "flavour"
    }],
    "yeast": "Wyeast 1056 - American Ale™"
  },
  "food_pairing": ["Oyster beignets", "Beef shin stew", "A Shakin' jesse"],
  "brewers_tips": "There's a lot of speciality malt in the mash. Make sure you take the run off nice and steady – increase the flow too much and pull in the bed at your peril.",
  "contributed_by": "Sasha <SashaMasondeCaires>"
}]

编辑1

一个答案部分有帮助,这是 my current pen

因为我多次将字符串写入类为 author 的 div

HTML 示例

<div class="author">Joe <crabshack></div>
<div class="author">juan <tacotruck></div>
<div class="author">Jesse <Canvas></div>

当前尝试的 JS

var user = document.getElementsByClassName('author').innerHTML;

var matches = user.match(/(.*)\s\<(.*)\>/);
var output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a>`;

document.body.innerHTML = output;

有问题的部分是var user = document.getElementsByClassName('author').innerHTML;


编辑3

当我尝试过

var user = document.querySelector(".author").innerHTML;

它只给了我该类的第一个,但我需要获得所有值。

最佳答案

这里是如何使用 javascript template literals ${variable}和一个正则表达式 /(.*)\s\<([a-z]*)\>/ .

堆栈片段

var user = "Sasha <SashaMasondeCaires>";
var matches = user.match(/(.*)\s\<(.*)\>/);
var output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}">@${matches[2]}</a>`;

document.body.innerHTML = output;


根据评论/jsfiddle 演示更新

这是您的演示代码的更新版本

var user = document.getElementsByClassName('author');
for (var i = 0; i < user.length; i++) {

  var matches = user[i].innerHTML.match(/(.*)\s\<([a-z]*)\>/);

  var output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a><br>`;

  document.body.innerHTML += output;

}
.author {
  display: none;
}
<div class="author">Joe <crabshack></div>
<div class="author">juan <tacotruck></div>
<div class="author">Joe <Canvas></div>
<div id="author">Juan Gallardo <JGallardo949></div>

关于javascript - 在已知符号之间提取字符串并将其分配为仅使用 javascript 的可重用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201624/

相关文章:

javascript - 如何防止子 div 中 anchor 的链接影响主 url?

javascript - 从 1.2.27 更新到 1.4.7 时 Angularjs 出现错误

javascript - HTML 选择列表 - 如何使用 jQuery 添加水印?

javascript - 在 React 中使用 Map 与 firebase

javascript - 使用参数在循环中从代码隐藏调用 JavaScript 函数

javascript - String 和 Array 泛型方法将在未来被弃用

javascript - 有没有办法动态更改 jqGrid 的单元格值?

javascript - 警告 : <Link/> is using incorrect casing. React 组件使用 PascalCase

javascript - Gatsby 似乎需要任何其他框架 10 倍的努力来添加一个图像 : What Am I Not Understanding?

javascript - selenium driver.execute_script 中的 Python var