I have one large string with '----begin----' and '----end----' through out the string. I am trying to seperate out each message and display them all inside a div as seperate messages. The following code gets me the first one but I am struggling with the logic to loop through a large string with many messages. How do I loop through the entire large string? Thank you.
var app = document.querySelector('#app');
function parseStr(str) {
var start_idx = str.indexOf('------Begin Message------');
var end_idx = str.indexOf('------End Message------');
app.innerHTML += '<p>' + str.substring(start_idx, start_idx + 27) + '</p>' + '<p>' +
str.substring(start_idx + 27, end_idx) + '</p><p>' +
str.substring(end_idx, end_idx + 23);
}
parseStr(str);
Below code will replace all your header and footer message text to <p> </p> tags giving you back a complete html string.
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<p>").replace(re2, "</p>");
return str;
}
OR if you want it this way
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<div><p>"+beginMsg+"</p><p>").replace(re2, "</p><p>"+endMsg+"</p></div>");
return str;
}
This while-loop should go through all messages:
function parseStr(str) {
let beginMsg = "------Begin Message------"
let endMsg = "------End Message------"
while ((let end_idx = str.indexOf(endMsg)) !== -1) {
let start_idx = str.indexOf(beginMsg);
/* start of your code */
app.innerHTML += '<p>' +
str.substring(start_idx, start_idx + beginMsg.length) +
'</p><p>' + str.substring(start_idx + beginMsg.length, end_idx) +
'</p><p>' + str.substring(end_idx, end_idx + endMsg.length);
/* end of your code */
str = str.slice(end_idx + endMsg.length);
}
}
"Large string" is a kind of trigger word for programmers. It matters if we're thinking megabytes, or just a few pages of text. In the "large, but not crazy large" case, just split on the delimiters.
const bigString = "------Begin Message------This is a message------End Message------------Begin Message------This is another message------End Message------"
const startDelim = "------Begin Message------"
const endDelim = "------End Message------"
// use a regex with a conjunction start or ("|") end delimiter
let regex = new RegExp(`${startDelim}|${endDelim}`);
// split, then filter for the messages, processing each as a <p>
let messages = bigString.split(regex).reduce((acc, el, i) => {
if (i%2) acc.push(`<p>${el}</p>`)
return acc
}, [])
console.log(messages)
If it's truly large, you might not want it in memory, and you might not want all of the parsed pieces all in the dom at once.
Related
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
Again some Problems.
I' get some values of a Textfield ,shown like them:
134.45 987.46 -89.10
224.67 127.26 -19.12
764.32 187.96 -78.25
...and so on...
I'm get them with
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text();
}
i need them in
1;134.45;987.46;-89.10< br /><<< yes also the break - it will written in a .TXT file >>>
2;224.67;127.26;-19.12< br />
3;764.32;187.96;-78.25< br />
...and so on...
I couldn't figure it out how to. seems insoluble :(
The hekp from "guest271314" was perfekt. i've built it a Little more dynamic.
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text().replace(/\s+X/, "");
var arr = getNP01TableData.split(/\s+/);
var _arr = [];
var index = 1;
for (var i = 1; i <= (arr.length-1)/3; i++) {
_arr.push( i + ";" + arr[index] + ";" + arr[index + 1] + ";" + arr[index + 2] + "<br />\n");
index = index + 3;
}
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
// ... code to write it back in txt file
}
Thanks a lot # all for your Help
Well, let's look at what you've got: you have a text block, with numbers separated by spaces. That's something we can work with.
The .split(" ") function will separate the numbers and put them in an array; you could do a
getNP01TableData.split(" ") and your result will be:
[" ", "134.45 ", "987.46 ", "-89.10", "
", "224.67 ", "127.26 ", "-19.12
", "764.32 ", "187.96 ", "-78.25" ]
And that definitely looks like something you can work with. Throw that bad boy into a loop:
var text = "";
for (var i = 0; i<arr.length/3; i++) {
text = text + i;
for (j = 0; j<3; j++) {
text=text+";"+arr[3*i + j]
}
text = text+"</br";
}
That might need a little fiddling, but you get the idea. Also, the .trim() function is useful for removing unwanted whitespace.
Try
var text = "134.45 987.46 -89.10 224.67 127.26 -19.12 764.32 187.96 -78.25";
var arr = $.map(text.split(" "), function (value, index) {
return value === "" ? null : [value]
});
var _arr = [];
_arr.push("1;" + arr.slice(0, 3).join(",").replace(/,/g, ";") + "<br />");
_arr.push("2;" + arr.slice(3, 6).join(",").replace(/,/g, ";") + "<br />");
_arr.push("3;" + arr.slice(6, 9).join(",").replace(/,/g, ";") + "<br />");
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
var reader = new FileReader();
reader.addEventListener("loadend", function (e) {
console.log(e.target.result);
});
reader.readAsText(file);
jsfiddle http://jsfiddle.net/guest271314/YpBxA/
I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE
I am creating hangman in javascript and I have (I think) successfully generated a random word from an array in a function, to check if it works I am trying to print the generated word in to the console but it doesn't seem to be working here's my code for the function
var word = function() //Random word is genereated from an array for the user to guess
{
GameWordArray = new Array(7);
GameWordArray[0] = "monitor";
GameWordArray[1] = "program";
GameWordArray[2] = "application";
GameWordArray[3] = "keyboard";
GameWordArray[4] = "javascript";
GameWordArray[5] = "gaming";
GameWordArray[6] = "network";
randno = Math.floor(Math.random() * GameWordArray.length);
document.write(GameWordArray[randno]);
console.log(word);
}
Thanks in advance :)
Here is an example on jsfiddle
var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
var word = words[Math.floor(Math.random() * words.length)];
console.log(word);
document.getElementById("word").textContent = word;
And to have it fit in directly with you present code:
var getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
Try using it this way:
var getRandomWord = (function () {
var gameWordArray = [];
gameWordArray.push("monitor");
gameWordArray.push("program");
gameWordArray.push("application");
gameWordArray.push("keyboard");
gameWordArray.push("javascript");
gameWordArray.push("gaming");
gameWordArray.push("network");
return function () {
var randNum, finalWord;
randNum = Math.floor(Math.random() * gameWordArray.length);
finalWord = gameWordArray[randNum];
return finalWord;
};
})();
DEMO: http://jsfiddle.net/bCEFA/1/
Instead of declaring an array with a predefined length, you might as well declare an empty one and add values to the end of it (with .push()). You could've also declared the array like:
var gameWordArray = ["monitor", "program", ...];
You were trying to print word (which I renamed to getRandomWord), which was/is a function. You probably meant to use console.log(gameWordArray[randno]), which should work.
That's what helped me to avoid duplicate alt tags for my online shop:
var items = ['word1', 'word2', 'word3'];
var item = items[Math.floor(Math.random() * items.length)];
I even doubled it and had a much more range on unique alt tags:
var items2 = ['word4', 'word5', 'word6'];
var item2 = items2[Math.floor(Math.random() * items2.length)];
And in the end it looked like this for my alt-tags on my product gallery thumbnails:
markup += '<div class="product-image-thumbnail"><img alt="' + alt + ' ' + item + ' ' + item2 + '" title="' + title + '" src="' + image + '" /></div>';
I'm working on a piece of code that uses regex expressions to do a find/replace for emoticons in a chat. However, I want to use the same array of values and output them as a reference.
The regex works fine for my searches, but when I tried to do a replace on the regex search string before I output it for my help, I still end up with a slash.
:\)
:\(
var emotes = [];
emotes[0] = new Array(':\\\)', 'happy.png');
emotes[1] = new Array(':\\\(', 'sad.png');
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
//Tried this and it doesn't seem to work
//var emote = emotes[i][0];
//emote.replace('\\', '');
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}
Your problem is that str.replace doesn't change the original variable but instead returns a new one. Try this out:
var emotes = [
[':\\\)', 'happy.png'],
[':\\\(', 'sad.png']
];
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
var emote = emotes[i][0].replace('\\', ''); // See what I did here?
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}