How to only get a certain portion of string? - javascript

I have this string that I receive from a get request:
Rekryteringstest för anställning
Det här är rekryteringstestet och samtidigt den sida som är data till programmet som ska skrivas
Uppgiften är ganska generellt skriven för att passa både för de som löser den i t ex Java och de som löser den som t ex en webbsida.
Skriv en lösning som:
1. Öppnar ett fönster (om inte resultatet visas i t ex webbläsare)
2. Laddar webbadresser till bilder med tillhörande kommentar (längst ner på den här sidan, nya bilder varje gång sidan laddas!)
3. Laddar och visar bilderna med tillhörande kommentar
4. Laddar om data (från den här sidan!) automatiskt var 30:e sekund, vid omladdning kan gamla bilder tas bort
5. Har en knapp för att manuellt trigga omladdning
6. Visar någon form av status när data laddas
7. Har en knapp för att avsluta applikationen
8. Har en 'Om'-dialog som visar kontaktinformation till dig
9. Lösningen ska vara enkel att testköra och om applicerbart EN körbar fil
A. Skicka in lösningen inklusive all kod till Bouvet
Hur applikationen ser ut är inte lika viktigt som hur applikationen
med tillhörande unit-test är skriven och fungerar.
Data:
https://images.unsplash.com/photo-1514125067037-8e669dd37638?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1e2adb26fb5dc49fc14efd7f6aeca128&auto=format&fit=crop&w=1650&q=80 Mer publik
---------- END OF THE RESPONSE STRING ------------
Every time i make a request, the https link and text after the link updates.
How can I easily get only these values in this big string?
I have tried this
let splittedArray = response.data.split( "Data:" );
And then I get this
<URL kommentar>
http://3.bp.blogspot.com/-_gbAWeYsKP4/T899GpY3CSI/AAAAAAAAACw/du8qLqu4xEo/s1600/empty.jpg Lådan
https://images.unsplash.com/photo-1514125067037-8e669dd37638?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1e2adb26fb5dc49fc14efd7f6aeca128&auto=format&fit=crop&w=1650&q=80 Mer publik
for example.
From here I would like to split the https links and the text afterwards in different parts so I can easily use them. At the moment I cannot use split because it is an array (the last part)

As per clarifications in comments, let's start with an example data here :
let splittedArray = [
"part to be discarded",
"<URL kommentar> http://3.bp.blogspot.com/-_gbAWeYsKP4/T899GpY3CSI/AAAAAAAAACw/du8qLqu4xEo/s1600/empty.jpg Lådan
https://images.unsplash.com/photo-1514125067037-8e669dd37638?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1e2adb26fb5dc49fc14efd7f6aeca128&auto=format&fit=crop&w=1650&q=80 Mer publik"
];
Then, you can't simply use split on the variable splittedArray.
If you want to do further manipulation on the second part (a string that actually contains the links), you need to get this part by referring it as splittedArray[1].
Then you can probably split it by space characters, and keep the ones starting with 'http'.
splittedArray[1].split(/\s+/)
let splittedArray = [
"part to be discarded",
"<URL kommentar> http://3.bp.blogspot.com/-_gbAWeYsKP4/T899GpY3CSI/AAAAAAAAACw/du8qLqu4xEo/s1600/empty.jpg Lådan \
https://images.unsplash.com/photo-1514125067037-8e669dd37638?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1e2adb26fb5dc49fc14efd7f6aeca128&auto=format&fit=crop&w=1650&q=80 Mer publik"
];
let splittedSecondPart = splittedArray[1].split(/\s+/);
let filteredByHttp = splittedSecondPart.filter(x => x.startsWith('http'));
console.log(filteredByHttp);

Related

Picking multiple random values from array [duplicate]

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 4 months ago.
Does anyone know how you can pick more than one random element from an array? The code below is a simplified version of my code, but i think it should be enough.
My code picks a random quote from the array, then fills a div with the random string. But here comes my question, how do i get a new quote when userinput === quoteRandom. The code should be able to do this multiple times.
let quote_array = [
'Gresset er grønnere på andre siden av gjerdet',
'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge',
'Jeg skulle ikke spise den, jeg skulle bare smake på den',
'Nøtter er ikke noe for en hel rev'
];
//Pick random quote
let quoteRandom = sitat_array[Math.floor(Math.random() * sitat_array.length)];
//Fill a div with quoteRandom
function fillQuote() {
div.innerText = quoteRandom;
}
//If userinput === quoteRandom
function newQuote() {
fillQuote();
}
If you mutate the origanal array with sort and pop, every time you can get a random element form the rest of the array. So you will never get a quote again, only all the elements are poped, and the array is reinitialized.
let quote_array = [];
function getaquote() {
if (quote_array.length === 0) {
quote_array = [
'Gresset er grønnere på andre siden av gjerdet',
'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge',
'Jeg skulle ikke spise den, jeg skulle bare smake på den',
'Nøtter er ikke noe for en hel rev'
];
}
quoteRandom1 = quote_array.sort(() => (Math.random() > .5) ? 1 : -1).pop();
console.log(quoteRandom1);
}
<button onclick="getaquote()">get a quote</button>

Impossible to unescape HTML with replace - Javascript

For one of my translation service, I need to keep my tags during the translation, so I've found a workaround that works like a charm :
var text = '<strong>Le doute commence à s’installer</strong> en toi. Tu as déjà fait ça auparavant avec d’autres hommes, ça marchait très bien, mais pas sur lui. Tu te demandes alors, découragée : <em>“Qu’est-ce qui ne va pas chez moi ? J’ai perdu la main ?”</em>'
// Now, we have to replace every tag by characters, and we will reuse the same characters to revert to their origins
var translateThis = text.replaceAll("<","dntch1").replaceAll(">","dntch2").replaceAll("/","dntch3");
console.log(translateThis);
But when I want to reverse the process, I have this problem :
var toNormal = translateThis.replaceAll("dntch1","<").replaceAll("dntch2",">").replaceAll("dntch3","/");
console.log(toNormal);
// output : "<strong>Le doute commence à s’installer</strong> en toi. Tu as déjà fait ça auparavant avec d’autres hommes, ça marchait très bien, mais pas sur lui. Tu te demandes alors, découragée : <em>“Qu’est-ce qui ne va pas chez moi ? J’ai perdu la main ?”</em>"
My string is full of unescaped HTML, but I want to revert to my HTML markers ...
I've already tried this :
function unEscape(htmlStr) {
htmlStr = htmlStr.replace(/</g , "<");
htmlStr = htmlStr.replace(/>/g , ">");
htmlStr = htmlStr.replace(/"/g , "\"");
htmlStr = htmlStr.replace(/'/g , "\'");
htmlStr = htmlStr.replace(/&/g , "&");
return htmlStr;
}
console.log(unEscape(toNormal));
// output : "<strong>Le doute commence à s’installer</strong> en toi. Tu as déjà fait ça auparavant avec d’autres hommes, ça marchait très bien, mais pas sur lui. Tu te demandes alors, découragée : <em>“Qu’est-ce qui ne va pas chez moi ? J’ai perdu la main ?”</em>"
I'm lost, maybe I've missed something ?
Thanks for your help !
PS : You can find below the expected output.
// Expected output : "<strong>Le doute commence à s’installer</strong> en toi. Tu as déjà fait ça auparavant avec d’autres hommes, ça marchait très bien, mais pas sur lui. Tu te demandes alors, découragée : <em>“Qu’est-ce qui ne va pas chez moi ? J’ai perdu la main ?”</em>"
Link to JSFiddle : https://jsfiddle.net/he25c3y4/3/

Angular how to convert a text string to html objects in typescript

Under my Angular app :
i ve a string like the following :
let mystr : "<p>Ceci c'est un texte aléatoire de test <a href='https://codemirror.net' title='https://codemirror.net' target='_blank'>ceci c'est un simple HYPERLINK</a> Ceci c'est un autre texte aléatoire de test Ceci c'est un autre texte aléatoire de test <a title='' target='_blank' href='http://testing.com/book.html?default=<script>alert(document.cookie)</script>'>Un autre hyperlink </a></p><p>Ceci c’est un hyperlink copié sur la même page:</p><p><a href='https://aaa.bb.tes.com/aide-et-support/fiche-assistance/31516/une-page-grise-saffiche-a-louverture-dun-fichier-excel-2010' title='se rendre sur la page Une page grise s’affiche à l’ouverture d’un fichier – Excel 2010'><span style='color:blue;'>Une page grise s’affiche à l’ouverture d’un fichier – Excel 2010</span></a></p>"
My purpose , is how to convert that string to html objects and manipulate them in typescript
(beofre appending them to the DOM with innerHtml)
And then be able to modify them before displaying in the view ;
For example i want to change all the titles attributes of all tags within that string
You can for example:
const mystr : "<p>Ceci c'est un texte aléatoire de test <a href='https://codemirror.net' title='https://codemirror.net' target='_blank'>ceci c'est un simple HYPERLINK</a> Ceci c'est un autre texte aléatoire de test Ceci c'est un autre texte aléatoire de test <a title='' target='_blank' href='http://testing.com/book.html?default=<script>alert(document.cookie)</script>'>Un autre hyperlink </a></p><p>Ceci c’est un hyperlink copié sur la même page:</p><p><a href='https://aaa.bb.tes.com/aide-et-support/fiche-assistance/31516/une-page-grise-saffiche-a-louverture-dun-fichier-excel-2010' title='se rendre sur la page Une page grise s’affiche à l’ouverture d’un fichier – Excel 2010'><span style='color:blue;'>Une page grise s’affiche à l’ouverture d’un fichier – Excel 2010</span></a></p>"
const el = document.createElement('div');
el.innerHTML = mystr;
const allA = el.querySelectorAll('a');
allA.forEach(a => console.log(a.getAttribute('title')));
and so forth...
You can use DomParser for this
const dom = new DOMParser().parseFromString('<h1>Hi</h1>','text/html')
const h1 = dom.querySelector('h1')
h1.setAttribute('hidden', 'true')
console.log(h1) // <h1 hidden="true">Hi</h1>

Why does JavaScript's string.split() not work correctly in certain cases?

I need to split a string of text into its component words, so I'm using a Regex to split it on the empty spaces (in a Typescript file, btw).
splitIntoWords(text: string) : Array<string> {
const separator = ' ';
const words = text.split(new RegExp(separator, 'g'));
return words;
}
This mostly works, but I've noticed that I regularly get words in the array that still contain spaces. If I copy the text into the Chrome console and split(' ') it I get the correct amount of words, but when I use the variable (even in the console) it invariably fails in some cases. I can't work out what the difference is. This is an example of my text:
"Le coronavirus en France : la décrue se poursuit en réanimation, la reprise économique au cœur des préoccupations. La mise en œuvre du plan de déconfinement élaboré par le gouvernement doit encore faire l’objet, jeudi, d’un « travail de concertation et d’adaptation aux réalités de terrain » avec les responsables et les élus locaux."
The regex never manages to split the substring "économique au" into two components, for instance. Does anyone know why this is happening?
It sounds like the whitespace is occasionally not just a plain space. You can split on all whitespace by using \s for the separator instead, which will match any whitespace, including space characters and tab characters.
const text = "Le coronavirus en France : la décrue se poursuit en réanimation, la reprise économique au cœur des préoccupations. La mise en œuvre du plan de déconfinement élaboré par le gouvernement doit encore faire l’objet, jeudi, d’un « travail de concertation et d’adaptation aux réalités de terrain » avec les responsables et les élus locaux.";
const words = text.split(/\s/);
console.log(words);
Another option would be to use match instead of split, and match non-whitespace characters.
const text = "Le coronavirus en France : la décrue se poursuit en réanimation, la reprise économique au cœur des préoccupations. La mise en œuvre du plan de déconfinement élaboré par le gouvernement doit encore faire l’objet, jeudi, d’un « travail de concertation et d’adaptation aux réalités de terrain » avec les responsables et les élus locaux.";
const words = text.match(/\S+/g);
console.log(words);

Regex - Exclude brackets and brackets with special key

I got this string:
[[Fil:Hoganas_hamn.jpg|miniatyr|Höganäs Hamn.]] [[Fil:Hoganas_hamn_kvickbadet.jpg|miniatyr|Höganäs Hamn - Kvickbadet.]] [[Fil:Höganäs Jefast ny redigerad-1.jpg|miniatyr|Jefasthuset sett från väster med en del av den nya bryggan vid Kvickbadet.]] '''Höganäs''' är en [[tätort]] och [[centralort]] i [[Höganäs kommun]] i [[Skåne län]]. Höganäs blev stad 1936. Ursprungligen är Höganäs ett [[fiskeläge]] kring vilket en [[gruvindustri]] utvecklades för brytning av [[kol (bränsle)|kol]] och [[lera|leror]] för tillverkning av [[eldfast]] [[keramik]] ([[Höganäskrus]]). Gruvindustrin är numera nedlagd.
I want to exclude every instance of [[FIL: + dynamic word]] and every [[, ]], but not exclude the word itself when its only [[word]] without the "FIL:" in it.
I've begun doing a regex for it but I'm stuck.
\[\[\Fil:|\]\]
The output Im after should look like this:
'''Höganäs''' är en tätort och centralort i Höganäs kommun i Skåne län. Höganäs blev stad 1936. Ursprungligen är Höganäs ett fiskeläge kring vilket en gruvindustri utvecklades för brytning av kol (bränsle)|kol och lera|leror för tillverkning av eldfast keramik (Höganäskrus). Gruvindustrin är numera nedlagd.
I have JQuery but think .replace should do the trick?
Try replacing all matches for this Regex with an empty string:
\[\[Fil:[^\]]*\]\]|\[\[|\]\]
To break this down:
\[\[Fil:[^\]]*\]\] matches [[Fil:...]]
\[\[ matches remaining [[
\]\] matches remaining ]]
| combines with OR
To get your exact output, you may need to strip some whitespace as well:
\[\[Fil:[^\]]*\]\]\s+|\[\[|\]\]
So, in JavaScript, you could write:
x.replace(/\[\[Fil:[^\]]*\]\]\s+|\[\[|\]\]/g, '');
Try this, maybe you want also to adjust spaces
var string = "[[Fil:Hoganas_hamn.jpg|miniatyr|Höganäs Hamn.]] [[Fil:Hoganas_hamn_kvickbadet.jpg|miniatyr|Höganäs Hamn - Kvickbadet.]] [[Fil:Höganäs Jefast ny redigerad-1.jpg|miniatyr|Jefasthuset sett från väster med en del av den nya bryggan vid Kvickbadet.]] '''Höganäs''' är en [[tätort]] och [[centralort]] i [[Höganäs kommun]] i [[Skåne län]]. Höganäs blev stad 1936. Ursprungligen är Höganäs ett [[fiskeläge]] kring vilket en [[gruvindustri]] utvecklades för brytning av [[kol (bränsle)|kol]] och [[lera|leror]] för tillverkning av [[eldfast]] [[keramik]] ([[Höganäskrus]]). Gruvindustrin är numera nedlagd.";
var result = string.replace(/\[\[Fil:.*?\]\]/g, '').replace(/\[\[(.*?)\]\]/g, '$1');
console.log(result);
You can use a regex like this
\[\[.*?\]\]
And then use the callback function version of replace to check if starts with Fil: then conditionally decide whether you want to return a blank string to erase it, or just the word itself.
Alternately, use 2 regexes. Replace the Fil: ones with a blank string first, and then the rest with just the word. You can use
\[\[(\w+)\]\]
Or something similar to catch the [[word]] ones and then replace it with a backreference to the word, i.e., \1 refers to what's in parentheses.

Categories

Resources