hello im doing something like how to replace dots inside quote in sentence with regex
var string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum. Nullam lacinia ipsum vitae enim consequat iaculis quis in augue. Phasellus fermentum congue blandit. Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris." Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc."';
// seperate the quotes
var quotes = string.match(/"(.)+?"/g);
var test = [];
// for each quotes
for (var i = quotes.length - 1; i >= 0; i--) {
// replace all the dot inside the quote
test[i] = quotes[i].replace(/\./g, '[dot]');
};
console.log(test);
lets say we already make the change with the regex, but im stuck at how can we join it back to the existing var string as my result is seperated in var test ? or theres a better way?
the output should be something like
Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum[dot]Nullam lacinia ipsum vitae enim consequat iaculis quis in augue[dot] Phasellus fermentum congue blandit[dot] Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris[dot]" Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc[dot]"
*ps im not sure the title is corrent
thanks
You could instead just split at ", do the replacement in every second array element, then join again:
var parts = string.split('"');
for (var i = 1; i < parts.length; i += 2) {
parts[i] = parts [i].replace(/\./g, '[dot]');
};
string = parts.join('"');
Since split will create an empty string at index 0 if the string starts with " this should work in all cases.
Note that the edge case of a trailing unmatched " will lead to every dot after that " to be replaced as well. If you do not want this, simply change the for condition to i < parts.length - 1.
JSFiddle Demo
Use regexp but with replace function:
string.replace(/"[^"]+"/g, function(m) {return m.replace(/\./g,"[dot]")})
Related
Iβve been trying to compare a block of lines for a few days now and still haven't found a solution. Actually, it seems that I can't split an array in a multidimensional array. Iβll give you full details should anyone know a better solution and would like to share it.
I have an html page including a textbox where I load data I want to use. It calls several action in an external javascript file to show executed data in three spans, here is a demo:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="..\..\..\css\style.css">
<script type="text/javaScript" src="..\..\js\javaction.js"></script>
</head>
<body>
<span id='CHANGINGvalue'><textarea rows="4" cols="20" id="loadingTEXTboxDATA" name="saveIT" onkeyup="actionJAVA1(document.getElementById('CHANGINGvalue'));actionJAVA2(document.getElementById('CHANGINGvalue'));" value="">load data inside this text box</textarea><div class="tooltipRIGHT">π<span class="tooltiptext">load data inside this text box</span></div></br></span>
<span id='showAREAdata1'>sss</span><br><br>
<span id='showAREAdata2'>ccc</span><br><br>
<span id='showAREAdata3'>hhh</span><br>
</body>
</html>
This is my javaction.js file:
function actionJAVA1(val)
{
var startingDATA = val.value;
if (startingDATA.includes("text to trigger action")) {
// first block of text to search trough
var i= 0;
var bloccoPERlinee = val.value.split("\n");
for ( i = 0; i < bloccoPERlinee.length; ++i)
{
if (bloccoPERlinee[i].includes('specific text search 1'))
{
// Yes, it's there
}
else {
// block of code to be executed if the condition is false
bloccoPERlinee[i] = ""
}
}
var SBLOCCOlinee1 = bloccoPERlinee.join("\n");
const removeEmptyLines = SBLOCCOlinee1.split(/\r?\n/).filter(line => line.trim() !== '').join('\n');
var eSEfunzionaLOpotevoTROVAREprima = removeEmptyLines.split('\n').filter(function (s) { return s.match('filtering word to eclude') })
var l = 0;
for ( l = 0; l < eSEfunzionaLOpotevoTROVAREprima.length; ++l)
{
eSEfunzionaLOpotevoTROVAREprima[l] = eSEfunzionaLOpotevoTROVAREprima[l].split('permit');
eSEfunzionaLOpotevoTROVAREprima[l] = eSEfunzionaLOpotevoTROVAREprima[l][1]
}
var ANCORAnonSOgestireARRAYmultilinea = eSEfunzionaLOpotevoTROVAREprima.join("\n");
document.getElementById('showAREAdata1').innerText = ANCORAnonSOgestireARRAYmultilinea;
// second block of text to search trough
var x= 0;
var bloccoPERlinee2 = val.value.split("\n");
for ( x = 0; x < bloccoPERlinee2.length; ++x)
{
if (bloccoPERlinee2[x].includes('alternative text to search trough'))
{
// Yes, it's there
}
else {
// block of code to be executed if the condition is false
bloccoPERlinee2[x] = ""
}
}
var SBLOCCOlinee2 = bloccoPERlinee2.join("\n");
const removeEmptyLines2 = SBLOCCOlinee2.split(/\r?\n/).filter(line => line.trim() !== '').join('\n');
var senzaCOMMENTI = removeEmptyLines2.split("\n");
document.getElementById('showAREAdata2').innerText = senzaCOMMENTI;
So far so good: I correctly managed to find the data I want that mainly are numeric value occurring in a different format and details in both arrays coming out from first (array1 named ANCORAnonSOgestireARRAYmultilinea) and second filtering actions (array2 named senzaCOMMENTI).
Besides that I do expect that in array1 should be just one match for any line in array 2, I now should compare them and merge matching data to show in span "showAREAdata3".
I thought to split them getting multdimensional array and if any value show up in both lines from array1 and array2 I should add at line value from arra1 last value from matching line in array2.
I start declaring a clone from those array and then trying to split array1 value by line and by given characters that in this case is a slash / but I managed to make it work just one per time. At second split it stop to work and the whole java function crash.
On array2 which should be even easier since it already comes in an array and I just should split by blank space to get multidimensional array is actually worse: I can not do it: it also crash the whole java function.
Thatβs in the specific what I tried in this last case:
var senzaCOMMENTIa = structuredClone(senzaCOMMENTI);
var senzaCOMMENTIa = Array.from(senzaCOMMENTIa);
const myArray = senzaCOMMENTIa.split(" ");}}
I may think to use map or for each β and I also tried a few solutions but did not succeded.
In the comments Swiffy asked for an example of how the input and outputs should be:
text box : mult line pasted text from external source
[
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut velit eget arcu eleifend consequat. Suspendisse tempor ut tellus ut fermentum. Donec sed euismod felis. Fusce venenatis viverra metus quis elementum. Etiam diam sapien, dignissim eget auctor a, bibendum vel nulla. Morbi non vulputate quam. Ut commodo venenatis ultrices. Phasellus a diam ultricies, iaculis enim at, lobortis nibh. Proin sodales tristique quam. Vivamus ornare sollicitudin mi, nec tincidunt neque mollis eget. Vivamus fermentum cursus felis, id pulvinar magna semper non. Duis id eros in massa dictum maximus. Nullam mollis risus non ligula consectetur, vel interdum massa laoreet. Aliquam nec finibus ex.
Praesent pretium hendrerit urna in finibus. Sed lacus ex, pharetra sed leo sed, molestie ultricies turpis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum viverra fermentum. Donec tincidunt libero tortor. Pellentesque facilisis, urna id viverra volutpat, massa erat finibus urna, sit amet rutrum felis lectus eu ex. Maecenas tincidunt orci molestie turpis ullamcorper, non feugiat felis tempus. Fusce rutrum urna sit amet mattis suscipit. Aliquam non sem sollicitudin, lacinia orci sit amet, finibus nisi. Mauris sollicitudin massa non massa sollicitudin pellentesque. Duis finibus ipsum et molestie tempor.
Maecenas
line1dataA/line1dataB
tempus
line2dataC/line2dataD data3b
. Vestibulum
line3dataE/line3dataF
Sed efficitur lorem vitae orci
data1a data2a data 3a(occasional) data4a
tincidunt volutpat.
data1b data2b data3b
data1c data2c data3c(occasional) data3d
Sed volutpat velit ut neque varius gravida a et elit. Ut egestas diam in urna varius, at volutpat mi rutrum. Sed dictum venenatis arcu, sit amet maximus tellus egestas vitae. Sed condimentum orci ac dolor dictum cursus. Suspendisse et eros velit. Donec rhoncus purus ex, nec volutpat elit viverra a. Integer efficitur non nibh eget congue.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi hendrerit bibendum lectus, at convallis sem cursus vel. Aliquam nec sem scelerisque, tempor elit sed, lacinia augue. Duis ex ipsum, tempus non placerat non, eleifend maximus est. Suspendisse sodales nulla a quam euismod, in tincidunt elit venenatis. Cras interdum vitae felis at vestibulum. Integer ac est ultricies, tincidunt ipsum in, tempor eros. Vivamus ultrices massa eleifend viverra auctor.
]
while being the array I've already found fro array1 such as:
array1: [line1dataA/line1dataB
line2dataC/line1dataD,
line3dataE/line3dataF,
so on,]
and for array2 such as:
array2: [data1a data2a data 3a(occasional) data4a, data1b data2b data3b, data1c data2c data3c(occasional) data4c, so on]
result of comparision:
line1dataA/line1dataB data4a
line2dataC/line2dataD data3b
line3dataE/line3dataF data4c
so on
With use of JavaScript/jQuery and RegEx I would like to remove all instances of the word 'Integer' from paragraph below and first word after the deleted word should be capitalized.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam elit
massa, maximus in turpis vel, viverra iaculis nisl. Nullam pulvinar mi
eu metus posuere, a porta ligula feugiat. Integer quis nunc neque.
Etiam sollicitudin diam in dolor sagittis pellentesque. Nunc placerat
sollicitudin purus. Proin mattis, quam sit amet pellentesque blandit,
urna erat mollis sapien, et vestibulum nunc mi sed orci. Integer ligula
tellus, maximus id orci quis, euismod consequat nulla.
My attempt so far for removing desired word:
var modified = $(".paragraph").html();
modified = modified.replace(/Integer\s/g, '');
But after that I don't know how to dynamically access the next word (from above example text word: 'quis' and 'ligula') and set it to be capitalized. One note: the word that needs to be deleted is always the same, but word after is always different.
To be sure of getting a capitalized word every time after removing Integer, use the following:
modified = modified.replace(/Integer\s+(\w)/g, function(fullMatch, capturedGroup) {
return capturedGroup.toUpperCase();
});
Note: This would even match Integer followed by Capitalised words. If you want to select only instances of Integer followed by lowercase words, then use [a-z] instead of \w in the above regex.
Not a regex but this one liner can fulfil your purpose.
let str = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam elit
massa, maximus in turpis vel, viverra iaculis nisl. Nullam pulvinar mi eu metus
posuere, a porta ligula feugiat. Integer quis nunc neque. Etiam sollicitudin diam
in dolor sagittis pellentesque. Nunc placerat sollicitudin purus. Proin mattis,
quam sit amet pellentesque blandit, urna erat mollis sapien, et vestibulum nunc
mised orci. Integer ligula tellus, maximus id orci quis, euismod consequat nulla.`;
str.split(/Integer\ /g).map(part=>{return part.charAt(0).toUpperCase() + part.substr(1)}).join("")
there is maybe a way with replace directly, but i would do it like this maybe:
let textResult;
do {
textResult = /Integer\s(.)/gs.exec(modified);
if (!textResult || !textResult[1]) {
textResult = null;
continue;
}
modified = modified.replace('Integer ' + textResult[1], textResult[1].toUpperCase());
} while (!!textResult);
This question already has answers here:
Regular expression to get a string between two strings in Javascript
(13 answers)
Closed 3 years ago.
I have this text
Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,
I want to get the text between <exclude> tags, I have this express but it does not work for me : /\<exclude\>/g
Note:
The tag could anything even something like #x it is just a delimiter to the that portion of the text.
How do I solve this problem?
Something like this should do the job:
<exclude>((?:[^<]|<(?!exclude>))*)(?=<exclude>)
^---1---^|^----------2----------^|^-----3-----^
+-----------4-----------+
This specifies the following:
Match the characters <exclude>.
Accept all characters that are not < or < not followed by exclude>.
The match may only end if it is followed by the characters <exclude>.
Capture the characters between the two tags in group 1.
For something simpler like the tag #x you can use the same principal:
#x((?:[^#]|#(?!x))*)(?=#x)
var text = `
Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,
`.trim();
var regex = /<exclude>((?:[^<]|<(?!exclude>))*)(?=<exclude>)/g;
while (match = regex.exec(text)) {
console.log(match[1]);
}
Assuming your data is correct and this isn't actually XML (for which you should use an XML parser instead). Given you specific example, this would work:
var str = `Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,`;
console.log(/<exclude>(.*?)<exclude>/gs.exec(str)[1]);
Your are going to look for something that matches <exclude> then we are going to group everything up to the next <exclude>. Although it makes no difference to this example, we use a lazy quantifier so if there are multiple pairs of <exclude> tags, you only match up to the next <exclude> and not the last <exclude>.
var str =
"Donec ante sapien, gravida id risus eget,\n" +
"<exclude>\n" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.\n" +
"<exclude>\n" +
"Donec ante sapien, gravida id risus eget,\n"
var regex = /<exclude>([\S\s]*?)<exclude>/g;
var found = regex.exec( str )[1];
console.log( found );
One way to design an expression for such output is to use capturing groups that most of answers are already using that.
Also, you can add other flags such as multiline or single line (depending on your input string) to your expression, as you wish. This tool might help you to do so, design and test your expressions and see how they work:
RegEx
(.*)(<exclude>)(.+)(<exclude>)(.*)
Graph
This graph shows how the expression would work:
Performance
This JavaScript snippet shows the performance of this expression using a simple 1-million times for loop.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = "Donec ante sapien, gravida id risus eget,\n" +
"<exclude>\n" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.\n" +
"<exclude>\n" +
"Donec ante sapien, gravida id risus eget,\n";
var regex = /(.+)(<exclude>)(.+)(<exclude>)(.+)/gms;
var match = string.replace(regex, "$3");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match πππ ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. π³ ");
Hi guys so i am doing an exercise and one of the questions has asked me to "Create an algorithm that puts words divided by space with a max 100 character line length" So basically there is an array of 1000 words or so and its suppose to put 100 words per line, and spaces don't count. It also says :
Given N words where N >= 1000
Create rows of words separated by spaces where row length >= 100
Once a word has been used it should be considered removed.
Add to a simple SPA
Now i have done this to the best of my ability but i created my own set of words, i was wondering how to change it to use an array and also how to remove it when its done been used. To be honset i am not sure what SPA means at all , so if someone can explain that, that would be fantastic.
const paragraph = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.",
lines = Math.round(paragraph.length / 100);
let line = 0;
for (let i = 0; lines > i; i++) {
document.body.innerHTML += paragraph.slice(line, line + 100) + '<br>';
line += 100;
}
So i got it to go through my set of words and it worked fine but i just need to change it to use an array which is what i am trying to figure out
Thanks for all the help
Let's say we have this text inside a single <p> that uses the entire screen space:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum
sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo
pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in
laoreet auctor. Donec in tortor in augue maximus fermentum et non erat.
Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor lectus, consectetur.
If we were using a smaller display, it would look like something this:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed vestibulum sem
consectetur, tempor massa quis, bibendum
mauris. Curabitur et leo pharetra,
condimentum mi vel, gravida mi. Integer
pulvinar nibh in laoreet auctor. Donec
in tortor in augue maximus fermentum et
non erat. Sed auctor feugiat dolor eget
efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor
lectus, consectetur.
The paragraph has now more lines than before. With that said, I want to convert this single paragraph into one <p> per line to apply different styling to each one of them, but also taking into acount that the number of lines can change from the viewport/browser window size. This is so that the text styling can be responsive.
HTML:
<p>Lorem ipsum dolor sit amet, consectetur</p>
<p>adipiscing elit. Sed vestibulum sem</p>
<p>consectetur, tempor massa quis, bibendum</p>
<p>mauris. Curabitur et leo pharetra,</p>
<p>condimentum mi vel, gravida mi. Integer</p>
<p>pulvinar nibh in laoreet auctor. Donec</p>
<p>in tortor in augue maximus fermentum et</p>
<p>non erat. Sed auctor feugiat dolor eget</p>
<p>efficitur. Vivamus nec urna lorem. Duis</p>
<p>lobortis semper tempor. Vestibulum dolor</p>
<p>lectus, consectetur.</p>
I'm looking for a pure JavaScript (aka no jQuery) solution.
document.body.addEventListener("load", function(){
var defaultCharacterWidth = 8; //8 px
var textboxWidth = document.querySelector(".orgText").offsetWidth;
var breakIndex = Math.floor(textboxWidth/defaultCharacterWidth);
var i = 0;
var savedIndex = 0;
var whitespace = 0;
document.querySelector(".orgText").textContent.match(/[\s\S]/g).forEach(function(element, index){
if (element.match(/\s/))
{
whitespace = index;
}
if (i == breakIndex)
{
i = -1;
//get nearest whitespace
document.querySelector(".textcontainer").innerHTML += "<p>" + document.querySelector(".orgText").value.slice(savedIndex, whitespace) + "</p>";
savedIndex = whitespace; //save the last whitespace
}
i++;
});
}, true);
<textarea class="orgText" style="overflow:hidden;width:100%">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in laoreet auctor. Donec in tortor in augue maximus fermentum et non erat. Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis lobortis semper tempor. Vestibulum dolor lectus, consectetur.
</textarea>
<div class="textcontainer">
</div>
This is a little testcode. It uses the fact that a textarea has a fixed character width. But that's not the case for most fonts. The above code iterates over every character and checks if it's exceeds the width of the container based upon the detection of a whitespace character.
You can also use the code below to calculate the width of a string.
function getPixelLengthOfString()
{
var tempNode = document.createElement("span");
tempNode.innerHTML = this;
document.body.appendChild(tempNode);
var stringPixelLength = tempNode.offsetWidth;
document.body.removeChild(tempNode);
return stringPixelLength;
}
These pieces of code should point you in a direction of the correct answer.