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"
Related
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!
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 a URL of Microsoft Translate Voice to get voice look like:
<audio controls autoplay>
<source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I’m Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>
The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?
If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:
// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
// Define your DOM elements
var getAudioBtn = document.getElementById('getAudioBtn'),
langSelect = document.getElementById("langSelect"),
langSource = document.getElementById("langSource"),
audioEl = document.getElementById('audioEl');
// Setup an event listener on the button
getAudioBtn.addEventListener('click', getContentTranslate);
// Setup an listener on the audio onended event
audioEl.addEventListener('ended', readChunkQueue);
var chunkQueue = [], // Queue of chunks of text to read
wordsPerChunk = 80, // Words per chunk
language = 'en'; // Default language
function getContentTranslate() {
// Store the language
language = langSelect.value;
// Empty the chunks array
chunkQueue = [];
// Split the text into words
var words = langSource.value.split(/ /g),
tmp = []; // Temporary array for creating a chunk
while(words.length) {
// If out temporary chunk is full, add it to the list
if (tmp.length === wordsPerChunk) {
chunkQueue.push(tmp.join(' '));
tmp = [];
}
tmp.push(words.shift());
}
if (tmp.length) {
chunkQueue.push(tmp.join(' '));
}
// Start reading these chunks
readChunkQueue();
}
function readChunkQueue() {
// If the list is empty, stop
if (!chunkQueue.length) {
return;
}
// Get the first chunk in the list
var chunk = chunkQueue.shift(),
url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
+ '&language=' + encodeURIComponent(language)
+ '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
+ '&text=' + encodeURIComponent(chunk);
// Set the URL as source for the audio element
audioEl.setAttribute('src', url);
}
});
<select id="langSelect">
<option value="en">English</option>
<option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>
<br>
<button id="getAudioBtn">GET AUDIO</button>
<br>
<audio id="audioEl" autoplay controls></audio>
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.
Problem: Selection#anchorOffset, Selection#baseOffset & Selection#focusOffset from time to time returns wrong values.
Expected behavior: Make double click on the second word in code snippet (feature). You should see alert 'anchor: feature'.
Question: How to get a correct value?
JSFiddle Demo: http://jsfiddle.net/v2mmabzm/5/
Demo:
$(document).ready(function()
{
var p = $('p.text-container')
p.css({ cursor: 'pointer' });
p.dblclick(function(e) {
var html = $(e.target).html();
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var selectedWord = $.trim(range.toString());
debugger;
var anchorOffset = range.anchorOffset;
var baseOffset = range.baseOffset;
var focusOffset = range.focusOffset;
alert('anchor: ' + html.substring(anchorOffset, anchorOffset + selectedWord.length));
alert('base: ' + html.substring(baseOffset, baseOffset + selectedWord.length));
alert('focus: ' + html.substring(focusOffset, focusOffset + selectedWord.length));
});
});
span.touched {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p class="text-container">
The future of manned space exploration and development of space depends critically on the creation of a dramatically more proficient propulsion architecture for in-space transportation. A very persuasive reason for investigating the applicability of nuclear power in rockets is the vast energy density gain of nuclear fuel when compared to chemical combustion energy. Current nuclear fusion efforts have focused on the generation of electric grid power and are wholly inappropriate for space transportation as the application of a reactor based fusion-electric system creates a colossal mass and heat rejection problem for space application. The Fusion Driven rocket (FDR) represents a revolutionary approach to fusion propulsion where the power source releases its energy directly into the propellant, not requiring conversion to electricity. It employs a solid lithium propellant that requires no significant tankage mass. The propellant is rapidly heated and accelerated to high exhaust velocity (> 30 km/s), while having no significant physical interaction with the spacecraft thereby avoiding damage to the rocket and limiting both the thermal heat load and radiator mass. In addition, it is believed that the FDR can be realized with little extrapolation from currently existing technology, at high specific power (~ 1 kW/kg), at a reasonable mass scale (<100 mt), and therefore cost. If realized, it would not only enable manned interplanetary space travel, it would allow it to become common place. The key to achieving all this stems from research at MSNW on the magnetically driven implosion of metal foils onto a magnetized plasma target to obtain fusion conditions. A logical extension of this work leads to a method that utilizes these metal shells (or liners) to not only achieve fusion conditions, but to serve as the propellant as well. Several low-mass, magnetically-driven metal liners are inductively driven to converge radially and axially and form a thick blanket surrounding the target plasmoid and compress the plasmoid to fusion conditions. Virtually all of the radiant, neutron and particle energy from the plasma is absorbed by the encapsulating, metal blanket thereby isolating the spacecraft from the fusion process and eliminating the need for large radiator mass. This energy, in addition to the intense Ohmic heating at peak magnetic field compression, is adequate to vaporize and ionize the metal blanket. The expansion of this hot, ionized metal propellant through a magnetically insulated nozzle produces high thrust at the optimal Isp. The energy from the fusion process, is thus utilized at very high efficiency. Expanding on the results from the phase I effort, phase II will focus on achieving three key criteria for the Fusion Driven Rocket to move forward for technological development:
</p>
</body>
Just change
var html = p.text();