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

时间:2018-07-06 00:38:25

标签: javascript

我要做什么

  • 我需要从返回的JSON值中获取所有twitter用户名,当前正在箭头内返回,例如<jgallardo949>
  • 将这些值分配为变量
  • 将该变量附加到twitter.com上的url
  • 在twitter用户名之前输入字符串,并将其分配为值
  • 结合其他生成的变量创建一个新变量,并将其包装在所需的HTML中
  • 在div中显示所需的新HTML
  • 对在任何div类为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在div中写入结果.author


当前代码

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类向divs写入字符串

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;

这只是给我第一堂课,但我需要获取所有值。

2 个答案:

答案 0 :(得分:1)

以下是使用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;


基于comment / 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>

答案 1 :(得分:0)

我想最容易解析的就是:

const [name, twitter] = input.split(">")[0].split("<").map(str => str.trim());

return `${name} <a href="twitter.com/${twitter}" >@${twitter}</a>`;