I want to extract the data in between the tag and, based on the content, return <View><Text>This is a Text</Text></View> or <View><Text>This is a Picture</Text></View>
The problem is that I don't know how to accumulate the result from the matches to Article, and then return {Article} as the final result.
In the case below, I should end up with that render:
<View><Text>This is a Text</Text></View>
<View><Text>This is a Picture</Text></View>
<View><Text>This is a Text</Text></View>
instead, I get the final result. I tried Article = Article + <View><Text>This is a Text</Text></View> and Article += <View><Text>This is a Text</Text></View> but they both failed.
export default class App extends React.Component {
render() {
let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str = '<RNVW><p>Markets are mixed in Asia, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China\'s shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney\'s S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs," Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China\'s report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>';
let match;
let Article;
while ((match = pattern.exec(str)) !== null) {
if (match[1].startsWith("<p>") !== false) {
Article = (
<View><Text>This is a Text</Text></View>
);
} else {
Article = (
<View><Text>This is a Picture</Text></View>
);
}
}
return (
<View style={styles.container}>
{Article}
</View>
);
}
}
Hey Vincent
you were doing one mistake with Article, you are trying to allocate a new item to Article every time instead, you should go with array and push new items every time in the array.
Made some changes in your code:
class App extends Component {
articleView = () => {
let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str ="<RNVW><p>Markets are mixed in Asia, with Japan's benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan's benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China's shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney's S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src=\"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png\"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>\"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs,\" Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China's report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>";
let match;
let Article = [];
while ((match = pattern.exec(str)) !== null) {
if (match[1].startsWith("<p>") !== false) {
Article.push(
<View>
<Text>This is a Text</Text>
</View>
);
} else {
Article.push(
<View>
<Text>This is a Picture</Text>
</View>
);
}
}
return Article;
};
render() {
return (
<View>
{this.articleView()}
</View>
);
}
}
it will give you desired output :)
I hope that's what you were looking for!
Thanks!
Related
I have simple ajax response, it prints each char in the string instead of each value how can I get each value with its key for id:its value etc...
success: function(msg) {
alert(msg);
msg = JSON.stringify(msg);
var result = JSON.parse(msg);
console.log("type is" + typeof (msg));
console.log("typeData" + Object.keys(result)
console.log("typeData" + Object.values(result)
);
the result:
"string(969) "{"id":"cmpl-6hJxW9ZC6bBWwGhBvFbcoAcuivO7v","object":"text_completion","created":1675782846,"model":"text-davinci-003","choices":[{"text":"\n\nTourism is an important industry that has a major impact on the economy of many countries. It involves the movement of people to different destinations for leisure, business, or educational purposes. Tourism can bring in a lot of money to a country, as tourists often spend money on accommodation, food, and activities. It can also create jobs in the hospitality industry, as well as in other sectors such as transportation and retail. Tourism can also help to promote cultural exchange, as people from different countries can learn about each other's cultures and customs. Additionally, tourism can help to preserve natural and cultural heritage sites, as well as promote environmental sustainability.","index":0,"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":129,"total_tokens":138}}\n"\n"
I am building a news website which gets data from an external server. The external server often sends me the links to particular tweets but I can't seem to find a way to convert them into an embedded tweet
(Please note stack overflow wont let me send shortened urls, therefore it is in quotations.)
The json that it sends me is like -
"Story": "ROME: Harry Kane scored twice as a buoyant England cruised through to the semi-finals of Euro 2020 with a one-sided 4-0 win over Ukraine in Rome on Saturday. Kane ended a worrying international scoring drought by netting in the 2-0 last-16 defeat of Germany in midweek and he put England ahead inside four minutes on a sweaty evening in the Italian capital. <strong>As it happened: Ukraine vs England</strong> Gareth Southgate's side then put this quarter-final tie out of sight with two more goals early in the second half, one from Harry Maguire before Kane netted again. Substitute Jordan Henderson got the fourth, and as Denmark lie in wait in the Wembley semi-final on Tuesday England will be confident of going on to reach a first ever European Championship final and even now claiming a first major international title since 1966. <p>�������������� England = semi-finalists ������#EURO2020 | #ENG https://twitter.com/EURO2020/status/1411427976047120387"</p>— UEFA EURO 2020 (#EURO2020) 1625346114000 The draw here was kind for them, with Ukraine surely as weak an opponent as they could hope to face in a quarter-final, a stage at which they have lost to the likes of Italy and Portugal in recent European Championships. However the statistics are impressive, with England having come through five games at this tournament all without conceding a goal. Some of their play in wide areas was outstanding, with Raheem Sterling and Jadon Sancho -- making his first start at the Euro -- too hot for Ukraine to handle. <p>⏰ RESULT ⏰What. A. Performance. �������������� Kane (2), Maguire & Henderson net in Rome as England reach EURO 2020 se… https://twitter.com/EURO2020/status/1411427976047120387"</p>— UEFA EURO 2020 (#EURO2020) 1625345627000 Kane, their captain, had gone close to eight hours without finding the net for his country but his opener here was his second in just eight minutes following the late strike that secured victory over Germany. Regardless of the opposition, their display at the Stadio Olimpico was a step-up in class in the final third to previous games at the Euro and they will be favourites at home against a Danish side who played their own quarter-final against the Czech Republic on Saturday in distant Baku. This will be the only match England play away from home in the competition and it marked quite a difference to their defeat of the Germans, which was watched by more than 40,000 supporters at Wembley, where coronavirus restrictions were eased. <p>�������������� Two-goal England hero Harry Kane takes the plaudits after inspiring the Three Lions in Rome ��#Heineken |… https://twitter.com/EURO2020/status/1411427976047120387"</p>— UEFA EURO 2020 (#EURO2020) 1625346478000 With Italy currently imposing a five-day quarantine on all arrivals from the United Kingdom, the number of England fans in Rome was limited to those already based in the European Union although they still made themselves heard in the crowd of under 12,000. They had plenty to celebrate, unlike their Ukrainian counterparts, as Andriy Shevchenko's team came up short in their bid to take the country to a first ever major tournament semi-final. They scraped out of their group and then edged 10-man Sweden in extra time in the last 16, and their chances of shocking England looked dead and buried when they fell behind early on. Sterling, who terrorised the Ukraine defence down the left, played in Kane who poked the ball past Georgiy Bushchan. Ukraine's giant striker Roman Yaremchuk forced a save from Jordan Pickford and a Declan Rice piledriver was kept out by Bushchan, with England looking comfortable. However Ukraine were a different proposition after injured defender Serhiy Kryvtsov was replaced by Dynamo Kiev winger Viktor Tsygankov in the 36th minute. They finished the first half strongly and more pessimistic England fans may have spent the interval reliving their exit from Euro 2016, when they lost to Iceland in the last 16 despite also having opened the scoring in the fourth minute. They need not have worried. England scored again less than a minute after the restart when a foul on Kane allowed Luke Shaw to deliver a free-kick from the left for Maguire to head in. Four minutes after that Sterling supplied the overlapping Shaw and he crossed for a rejuvenated Kane to head home. The Tottenham star nearly had his hat-trick, a stinging volley producing a fine save from Bushchan. From Mason Mount's resulting corner came the fourth goal, another header, this time from Henderson, the first of five substitutes sent on by Southgate who would have been thinking about the semi-final long before this quarter-final was officially over. ",
Edit: Based on the reply below this. Let me clarify My server sends me data in the form of json objects with strings in it. I pass this data using ejs tags to their appropriate location to get rendered. I am asking how can i convert every twitter url that winds up in my json object to an embedded tweet.
Edit: This is the json that i received from the server I can render that just fine on my webpage but i cant seem to find a way to convert the hyperlinks to embeded tweet
just add "https://publish.twitter.com/oembed?" before your url as mentioned here.
you can also customize the embedded tweet as described in the link.
the response would be something like
{
"url": "https://twitter.com/Interior/status/507185938620219395",
"author_name": "US Dept of Interior",
"author_url": "https://twitter.com/Interior",
"html": "<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Happy 50th anniversary to the Wilderness Act! Here's a great wilderness photo from #YosemiteNPS. #Wilderness50 pic.twitter.com/HMhbyTg18X</p>— US Dept of Interior (#Interior) September 3, 2014</blockquote>n<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>",
"width": 550,
"height": null,
"type": "rich",
"cache_age": "3153600000",
"provider_name": "Twitter",
"provider_url": "https://twitter.com",
"version": "1.0"
}
and you can use the html property as embed tweet.
I think this should work for you. Twitter provides an api for creating embed html from a tweet url.
const axios = require('axios');
const main = async () => {
const tweetURL = 'https://twitter.com/thejackbeyer/status/1411522480775204866?s=20';
try {
const response = await axios.get(`https://publish.twitter.com/oembed?url=${tweetURL}`);
console.log(response.data.html);
} catch (error) {
console.error(error);
}
}
main();
I would like to ask for help in learning how to replace a 3 different combinations of characters from a string, and replace them with a carriage return.
The character combinations are:
++~
~~+
+~\
I would like to be able to replace those combinations with a carriage return.
String example:
Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\
Any help with code examples would be greatly appreciated.
Thank you!
UPDATE
I have a starter function, it does the work, but I am not sure if this is an extensible solution.
function findAndReplace() {
var string = 'Addendum and/or contract providing additional event details and conditions. Capacity for the King St. concerts is 3,645 persons with additional safety conditions as per Addendum.++~ Addendum and/or contract providing additional event details and conditions on file in Madison Parks.++~ Notification: Event participants must be notified prior to the race that they must adhere to the traffic signals. They are not allowed to stop traffic during the event.++~ Organizer must notify hotels, businesses and residents along the approved bike route. Include estimated time periods when athletics will "block" access and provide day-off contact information.++~ Call the Sayle Street Garage, 608-266-4767, 1120 Sayle St, to make arrangements to pick up and return barricades required for event. There may be charges for this equipment.++~ ';
var target1 = '++~ ';
var target2 = '~~+ ';
var target3 = '+~\\ ';
var replacement = '\n';
var i = 0, length = string.length;
for (i; i < length; i++) {
string = string.replace(target1, replacement)
.replace(target2, replacement)
.replace(target3, replacement);
}
return string;
}
console.log(findAndReplace());
This simple regex will replace all occurance in the string.
/\+\+~|~~\+|\+~\\/g
You first need to escape the \ in the string so this abc+~\monkey would become this abc+~\\monkey.
Then you can use split to split the items. map to do some cleanup on the items, then join to insert your carriage return \r\n
let str = 'Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\\'
str = str.split(/\+\+~|~~\+|\+~\\/g).map(i => i.trim()).join('\r\n')
console.log(str)
You may try to use the replace function in js:-
let sampleStr = `Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\ `;
let replacedString = sampleStr.replace(/\++~/g, '\r').replace(/~~\+/g,'\r').replace(/\+~\\/g,'\r');
alert(replacedString);
You can try this
const str = "Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\\ ";
console.log(str.replace(/\+\+~|~~\+|\+~\\/g, '<new symbol>'));
I have the show more/less done but it's based on the length of the text. What happens is, as there are characters that take more space than others, the "show more/less" words show in different places, not always at the end of the line. Sometimes I get something like this:
With the rest of the line free.
I want to check this based on the actual number of lines instead of the text length.
Here's a codePen of what I've got and below a code snippet:
$(document).ready(function() {
function splitText(text) {
var textBreak = textLimit;
var first = text.substring(0, textBreak);
var second = text.substring(textBreak);
var aux = second.substring(0, second.indexOf(" "));
var spaceIndex = second.indexOf(" ");
second = " " + second.substring(spaceIndex + 1);
first = first.substring(0, textBreak) + aux;
var bothTextes = [first, second];
return bothTextes;
}
var textLimit = 400;
var text = $("#companyDetails").html();
if (text.length > textLimit) {
var textArray = splitText(text);
$("#companyDetails").text(textArray[0]);
$("#companyDetails").append("<span onclick=\"expandText()\" class='show-more'>...<span class=\"red\">show more</span></span>");
$("#companyDetails").append("<span style=\"display: none\" class='rest-of-description'>" + textArray[1] + "</span>");
$("#companyDetails").append("<span onclick=\"collapseText()\" style=\"display: none\" class='red show-less'> show less </span>");
} else {
$("#companyDetails").text(text);
}
});
function expandText() {
$(".rest-of-description").show();
$(".show-less").show();
$(".show-more").hide();
}
function collapseText() {
$(".rest-of-description").hide();
$(".show-less").hide();
$(".show-more").show();
}
#companyDetails {
border: 1px solid red
}
.red {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="companyDetails">
We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for. I case you didn't read, here it is again: We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for.
</div>
EDIT
So after #TomHood's suggestion, I can now have the line count. However, I still need to know where am I going to break the text. I can't get the final word of a specific line...
You can do this by restricting the max-height in css, based on the line-height:
#companyDetails {
border: 1px solid red;
line-height: 1.2em;
max-height: 4.8em; //4.8 = 4 lines
overflow: hidden;
}
then you just need to change the max-height property in javascript/jQuery
$('#showMore').click(function(){
$('#companyDetails').css('max-height', 'none');
});
http://codepen.io/anon/pen/KVGpwd
You could use the following markup:
<div class="companyDetailsWrap">
<p class="companyDetailsText">We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for. I case you didn't read, here it is again: We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for.</p>
</div>
Then use this script:
$(function () {
var initial = $('.companyDetailsText').text();
$('.companyDetailsText').text(initial);
while($('.companyDetailsText').outerHeight() > $('.companyDetailsWrap').height()) {
$('.companyDetailsText').text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
$(window).resize(function() {
$('.companyDetailsText').text(initial);
while($('.companyDetailsText').outerHeight() > $('.companyDetailsWrap').height()) {
$('.companyDetailsText').text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
});
});
This is basically listening to see if the height of your text exceeds the container, rather than using character count. You will just need to set your desired height in css on .companyDetailsWrap.
I am having problems with this code and the console states that the function is not defined. I can't seem to understand why though.
<script>
var month = new Date();
var current_month = month.getMonth();
var monthlist = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var YOY = 11;
var org_traffic = 1,256;
var HD = 12;
var VIN = 30;
var emails = 20;
function analysis() {
if (YOY >= 10) {
if (HD >= 5) {
if (VIN >= 5) {
if (emails >= 5) {
document.write("This month we saw that overall organic traffic has improved "+YOY+"% compared to last year, bringing in a total of "+org_traffic+" visits in "+(monthlist[current_month - 1])+", accompanied by the growth we're seeing with H&D visits, VIN views, and email leads!");
}
else {
document.write("This month we saw that overall organic traffic has improved "+YOY+"% compared to last year, bringing in a total of "+org_traffic+" visits in "+(monthlist[current_month - 1])+", accompanied by the growth we're seeing with H&D visits,and VIN views!");
}
}
else if (VIN >= 0) {
document.write("This month we saw that overall organic traffic has improved "+YOY+"% compared to last year, bringing in a total of "+org_traffic+" visits in "+(monthlist[current_month - 1])+", accompanied by the growth we're seeing with H&D visits!<br/>We do see a modest "+VIN+"% growth in VIN views, which I'll be aiming to improve over the coming quarter.");
}
else if (VIN <= 0) {
document.write("This month we saw that overall organic traffic has improved "+YOY+"% compared to last year, bringing in a total of "+org_traffic+" visits in "+(monthlist[current_month - 1])+", accompanied by the growth we're seeing with H&D visits!<br/>Unfortuntately we did see a decrease in VIN views by about "+VIN+"%, which I'll be aiming to improve over the coming quarter.");
}
}
else {
document.write("This month we saw that overall organic traffic has improved "+YOY+"% compared to last year, bringing in a total of "+org_traffic+" visits in "+(monthlist[current_month - 1])+". Unfortunately our engagement metircs don't seem to be following suit and therefore will become a major focus of mine moving forward to turn our growing traffic numbers into an engaged visitor base.");
}
}
else if (YOY >= 0) {
document.write("This month we saw a modest "+YOY+"% growth in overall organic traffic compared to last year, bringing in a total of "+org_traffic+" visits. While any growth is definitely a positive, I would like to see this number improve over the coming quarter and will be taking proactive steps to turn up the dial on this trend.");
}
else if (YOY <= 0) {
document.write("This month we saw a decrease in overall organic traffic compared to year by -"+YOY+"%. This is definitely not the trend I am looking to see from our efforts on the website. I'll be conducting a thorough investigation to see what factors may be causing this downward trend. I'll be sure to keep you up to date as I dig deeper into the root cause of this trend.");
}
}
document.write(analysis());
</script>
I'd love any suggestions that I may try to make this function properly.
You've got a comma var org_traffic = 1,256; should be var org_traffic = 1256;
Fix that invalid assignment, and then the code wont' break before hitting your function definition. :)
There is some weird stuff going on.
Your comma in var org_traffic = 1, 256 does not belong there.
Your function does not return a string, so you just call analysis() and not write the function, because the functions return value is undefined.
And console will always log undefined for document.write(), because it has no return value, too.