Insert line break every 3 lines in javascript? - javascript

Hi I'm still a newbie at javascript so I want to create a script that inserts a line break after every 3 lines. So here's my code I got so far
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.toString().match(/.{3}/g).join('</br>');
console.log(newNum);
It is doing it wrong. It seems to be inserting every 3characters instead of lines. Can anyone help me fix the code?

You can use the replace function. Try the below code.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/(.*\n.*\n.*\n)/g, '$1<br>');
console.log(newNum);
EDIT
I have made a few changes to the RegEx in the code below. This will allow you to specify the number of lines between which <br> need to be added.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/((.*\n){3})/g, '$1<br>');
console.log(newNum);
In the above RegEx, the .* will match all characters till the end of line and the \n will match the new line character.
(.*\n){3}
I have enclosed this in parenthesis to mark it as a group and used {3} to indicate that the preceding group repeats 3 times.
((.*\n){3})
Then the whole RegEx is enclosed in a parenthesis to use it as the first matched group that can be referenced in the replace section using $1.
You can replace the {3} with any number.

You should avoid using string manipulation when using HTML string. Also using BR to break line is not a good idea as well. You should use a block element instead.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var content = document.querySelector('.content');
var urls = num.split('\n');
var temp;
for(var i = 0; i< urls.length; i++) {
if(!temp || (i+1) % 3 === 0) {
if (temp) content.appendChild(temp);
temp = document.createElement('div');
}
var span = document.createElement('span');
span.classList.add('link')
span.innerHTML = urls[i];
temp.appendChild(span);
}
content.appendChild(temp);
.link {
margin: 5px;
}
<div class='content'>
Reference:
Is it sometimes bad to use <BR />?

Related

JS What's the fastest way to display one specific line of a list?

In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));

Replace string with condition in google script

in google script I am trying to replace a %string basing on the character following it.
I've tried using:
var indexOfPercent = newString.indexOf("%");
and then check the character of indexOfPercent+1, but indexOf returns only the first occurrence of '%'.
How can I get all occurrences? Maybe there is easier way to do that (regular expressions)?
EDIT:
Finally I want to replace all my % occurrences to %%, but not if percent sign was part of %# or %#.
To sum up: my string: Test%# Test2%s Test3%. should look like: Test%# Test2%s Test3%%.
I've tried using something like this:
//?!n Matches any string that is not followed by a specific string n
//(x|y) Find any of the alternatives specified
var newString = newString.replace(\%?![s]|\%?![%], "%%")
but it didn't find any strings. I am not familiar with regex's, so maybe it is a simple mistake.
Thanks
Try this code:
// replace all '%'
var StrPercent = '%100%ffff%';
var StrNoPersent = StrPercent.replace(/\%/g,'');
Logger.log(StrNoPersent); // 100ffff
Look for more info here
Edit
In your case you need RegEx with the character not followed by group of characters. Similiar question was asked here:
Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?
Thy this code:
function RegexNotFollowedBy() {
var sample = ['Test%#',
'Test2%s',
'Test3%',
'%Test4%'];
var RegEx = /%(?!s|#)/g;
var Replace = "%%";
var str, newStr;
for (var i = 0; i < sample.length; i++) {
str = sample[i];
newStr = str.replace(RegEx, Replace);
Logger.log(newStr);
}
}
I'll explain expression /%(?!s|#)/g:
% -- look '%'
(text1|text2|text3...|textN) -- not followed by text1, 2 etc.
g -- look for any accurance of searched text

Split a string of HTML into an array by particular tags

Given this HTML as a string "html", how can I split it into an array where each header <h marks the start of an element?
Begin with this:
<h1>A</h1>
<h2>B</h2>
<p>Foobar</p>
<h3>C</h3>
Result:
["<h1>A</h1>", "<h2>B</h2><p>Foobar</p>", "<h3>C</h3>"]
What I've tried:
I wanted to use Array.split() with a regex, but the result splits each <h into its own element. I need to figure out how to capture from the start of one <h until the next <h. Then include the first one but exclude the second one.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
var foo = html.split(/(<h)/);
Edit: Regex is not a requirement in anyway, it's just the only solution that I thought would work for generally splitting HTML strings in this way.
In your example you can use:
/
<h // Match literal <h
(.) // Match any character and save in a group
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/h // Match literal </h
\1 // Match what previous grouped in (.)
> // Match literal >
/g
var str = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>'
str.match(/<h(.)>.*?<\/h\1>/g); // ["<h1>A</h1>", "<h2>B</h2>", "<h3>C</h3>"]
But please don't parse HTML with regexp, read RegEx match open tags except XHTML self-contained tags
From the comments to the question, this seems to be the task:
I'm taking dynamic markdown that I'm scraping from GitHub. Then I want to render it to HTML, but wrap every title element in a ReactJS <WayPoint> component.
The following is a completely library-agnostic, DOM-API based solution.
function waypointify(html) {
var div = document.createElement("div"), nodes;
// parse HTML and convert into an array (instead of NodeList)
div.innerHTML = html;
nodes = [].slice.call(div.childNodes);
// add <waypoint> elements and distribute nodes by headings
div.innerHTML = "";
nodes.forEach(function (node) {
if (!div.lastChild || /^h[1-6]$/i.test(node.nodeName)) {
div.appendChild( document.createElement("waypoint") );
}
div.lastChild.appendChild(node);
});
return div.innerHTML;
}
Doing the same in a modern library with less lines of code is absolutely possible, see it as a challenge.
This is what it produces with your sample input:
<waypoint><h1>A</h1></waypoint>
<waypoint><h2>B</h2><p>Foobar</p></waypoint>
<waypoint><h3>C</h3></waypoint>
I'm sure someone could reduce the for loop to put the angle brackets back in but this is how I'd do it.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
//split on ><
var arr = html.split(/></g);
//split removes the >< so we need to determine where to put them back in.
for(var i = 0; i < arr.length; i++){
if(arr[i].substring(0, 1) != '<'){
arr[i] = '<' + arr[i];
}
if(arr[i].slice(-1) != '>'){
arr[i] = arr[i] + '>';
}
}
Additionally, we could actually remove the first and last bracket, do the split and then replace the angle brackets to the whole thing.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
//remove first and last characters
html = html.substring(1, html.length-1);
//do the split on ><
var arr = html.split(/></g);
//add the brackets back in
for(var i = 0; i < arr.length; i++){
arr[i] = '<' + arr[i] + '>';
}
Oh, of course this will fail with elements that have no content.
Hi I used this function to convert html String Dom in array
static getArrayTagsHtmlString(str){
let htmlSplit = str.split(">")
let arrayElements = []
let nodeElement =""
htmlSplit.forEach((element)=>{
if (element.includes("<")) {
nodeElement = element+">"
}else{
nodeElement = element
}
arrayElements.push(nodeElement)
})
return arrayElements
}
Happy code

Removing last comma

I read content from a file and then write it another file after editing . While editing , for each read line i put a comma at the end of line and then write it to the file. For the last read line i do not want to write a comma. How should i do it.?
while(!inputFile.AtEndOfStream){
var readLine = inputFile.ReadLine();
var omitChars = new RegExp("#define").test(readLine);
if(omitChars==1){
var stringReadPosition = readLine.substr(8);
var finalString = stringReadPosition.replace(/\s+/g, ': ');
asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
}
}
outputFile.Write("};\r\n");
inputFile.Close();
outputFile.Close();
}
You can use substring in order to remove the last character of the string after you have formed the string:
finalString = finalString.substring(0, finalString.length - 1);
An alternative would be the use of slice, taking into consideration that negative indices are relative to the end of the string:
finalString = finalString.slice(0,-1);
Take a look in this question for more.
UPDATE: For your case, you could check whether or not you have reached the EOF - meaning you have read the last line, and then apply slice or substring:
//....
var stringReadPosition = readLine.substr(8);
var finalString = stringReadPosition.replace(/\s+/g, ': ');
//Check if stream reached EOF.
if(inputFile.AtEndOfStream) {
finalString = finalString.slice(0,-1);
}
asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
//....
try this asd = asd.replace(/,\s*$/, "");
this will remove last comma, I have tried this, its working .Check if it works in ur code.
Try this code inside while loop

Regular expression to separate smileys from text

I am trying to create a regular expression in Javascript to separate any occurrence of :) from the surrounding text.
Given the following:
:)This is a line of text :) with several smileys in it :). So there.,:):)
I would like to get the resulting 8 groups:
:)
This is a line of text
:)
with several smileys in it
:)
. So there.,
:)
:)
At the moment I use ([^:)]+) which only groups the surrounding text without the smileys. What adjustment could I make so that the smileys are also grouped?
I'd suggest:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/);
console.log(matches);​
JS Fiddle demo.
Added filtering to remove the empty matches from the above:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/),
matched = [];
for (var i = 0, len = matches.length; i < len; i++) {
if (matches[i].length) {
matched.push(matches[i]);
}
}
console.log(matched);​
JS Fiddle demo.
A further version, with actual on-screen output:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/),
matched = [], li,
list = document.createElement('ol');
document.body.appendChild(list);
for (var i = 0, len = matches.length; i < len; i++) {
if (matches[i].length) {
matched.push(matches[i]);
li = document.createElement('li');
txt = document.createTextNode(matches[i]);
li.appendChild(txt);
list.appendChild(li);
}
}
console.log(matched);​
JS Fiddle demo.
split:
var string = "Given the following: :)This is a line of text :) with several smileys in it :). So there.,:):)";
var groups = string.split(/:\)/);
This will return an array in which each element is a part of text without :).
Since the text has been split on each :), we can construct the result you want by adding a :) between each parts of text:
var parts = [groups[0]];
for (var i = 1; i < groups.length; ++i) {
parts.push(':)');
parts.push(groups[i]);
}
The result is this:
:)
This is a line of text
:)
with several smileys in it
:)
. So there.,
:)
:)
Try this here: http://jsfiddle.net/Gxr6U/3/
If you want to replace smilies by images, you could do this:
var frags = document.createDocumentFragment();
frags.appendChild(document.createTextNode(groups[0]));
for (var i = 1; i < groups.length; ++i) {
var img = document.createElement('img');
img.src='http://../smiley.png';
frags.push(img);
frags.appendChild(document.createTextNode(groups[i]));
}
If you just want to remove smilies:
var text = groups.join('');
The following will successfully group the string you mentioned as you want:
your_match = your_string.match(/(:\)|[^:)]*)/g)
However, like your original RegExp, you will encounter problems if a : or ) appears without being in a smiley. These characters will disappear from the match groups if not within a smiley.
You can use this pattern:
/:\)|(?:[^:]+|:(?!\)))+/g
This matches either :) or any character except : or a : that is not followed a ).

Categories

Resources