Trying to add linebreaks to every found pattern in string - javascript

I have a long string of email addresses, and I need to add a line break to the end of every ".edu" in javascript and write it to the innerHTML of a I'm not very sure how to do this though. Any thoughts?

Assuming that you don't have any separator you can use the '.edu' as a separator because you know that It will be founded in any email you have, so you can try something like this:
JS
var str = 'mail1#mail1.edumail2#mail2.edumail3#mail.edumail4#mail4.edumail5#mail5.edu';
var emails = str.split('.edu');
var result = document.getElementById('result');
for(var i = 0, len = emails.length; i < len; i++){
if(emails[i]){
result.innerHTML += '<p>'+ emails[i] +'.edu</p>';
}
}
HTML
<div id="result">
</div>
I don't know exactly what you mean about a 'line break' but this solution fits for what you need, you just need to replace the string that is placed in the result div for the whatever you want show.
Check out this codepen.

Related

javascript make paragraph link

i use this javascript code to editing paragraph if it have links the code will make the link active to click by adding html href element
my problem is the result of this code be in one line
i want the paragraph result stay paragraph not 1 line
any idea?
thanks all
var collection = document.getElementsByClassName("Edit_desc");
for (let i=0; i<collection.length; i++) {
//Regex Expresson to match general URL used frequently.
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
//Creating Regex Object with the Regex Expression
var regex = new RegExp(expression);
//Fetch words from the Text Area , array named 'input_text_words' will contain all words separately
var input_text_words = collection[i].textContent.trim().split(/\s+/);
var input_text_number_of_words = input_text_words.length;
//Empty Paragraph Element
var paragraphElement = "";
//Traversing the words array
for(var index = 0 ; index < input_text_number_of_words ; index++){
//If the word matches the URL regex than print using so that link may appear.
if(input_text_words[index].match(regex)){
paragraphElement += ''+input_text_words[index]+'';
}
//Else if the word is not any url , simply print.
else{
paragraphElement += input_text_words[index];
}
if(index != input_text_number_of_words-1){
paragraphElement += ' ';
}
}
//Finally show the modified text in tha empty paragraph element.
collection[i].innerHTML = paragraphElement;
}
I suppose that your spaces are not caused by html tags like <br/>
So the problem is the splitting you do :
var input_text_words = collection[i].textContent.trim().split(/\s+/);
The ("string1 string2\nstring3").split(/\s+/); expression splittes the string into 3 items. Making you lose the lines part...
As a solution i suggest you use another regex that partially solves the problem
.split(/[^\S\r\n]/g)
witch i got from this guy
But this solution has possible issues, if the linke is at the start of the paragraph or if you can have a link with lines inside it ( done by a text-area for example ) that wont be selected. So be sure to check what do u need exactly and adjust the regex to something that suites you.

Replace text in html string

I'm trying to write a regular expression for following criteria
The source string might optionally contain an html code. Which should be preserved, everything outside tag should replace with a static text.
function replaceCode( mystring ){
var replaceWith = "Hello!!!" ;
//do something with mystring here..
}
var string1 = "<span>Title</span> A small note" ;
var string2 = "Another big note" ;
alert( replaceCode(string1) ) ;
alert( replaceCode(string2) ) ;
Resultant strings must be
//string1 must become
<span>Title</span> Hello!!!
//string2 must become
Hello!!!
You may do following:
var yourString = "<span>Title</span> any text to replace";
var yourReplacement = "Hello!";
//Split by html tags
var tokens = yourString.split(/<\w+>\w+<\/\w+>/);
for (var i = 0; i < tokens.lenght; i++) {
yourString = yourString.replace(tokens[i], yourReplacement);
}
This, however, is probably not the best solution and will not work for nested tags but fit your examples.

Javascript Shortcode Parse

I need to parse following shortcode, for example my shortcode is :
[shortcode one=this two=is three=myshortcode]
I want to get this, is and myshortcode and add to array so it will :
['this', 'is', 'myshortcode']
NOTE : I know generally shortcode parameter marked with " and " ( ie [shortcode one="this" two="is" three="myshortcode"] ), but I need to parse shortcode above without ""
Any help really appreciated
I'm assuming you want to parse the first string with Regex and output the three elements in order to add them to an array later. That seems rather simple, or am I misunderstanding what you need? I'm assuming the word shortcodeis as it will be in your string. You'd probably need two regex operations if you haven't located and isolated the shortcode string yet that you posted above:
/\[shortcode((?: \S+=\S+)+)\]/
Replacement: "$1"
If you already have the code exactly as you posted it, then you can skip the regex above. At any rate, you'll have end with the following regex:
/ \S+=(\S+)(?:$| )/g
You can then add all the matches to your array.
If this is is not what you're looking for, then perhaps a more real example of your code would help.
Here you go I have built a perfectly scalable solution for you. The solution works for any number of parameters.
function myFunction() {
var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]";
var output = new Array();
var res = str.split("=");
for (i = 1; i < res.length; i++) {
var temp = res[i].split(" ");
if(i == res.length-1){
temp[0] = temp[0].substring(0,temp[0].length-1);
}
output.push(temp[0]);
}
document.getElementById("demo").innerHTML = output;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);
You can try the above code.
Here's my solution: https://jsfiddle.net/t6rLv74u/
Firstly, remove the [shortcode and trailing ]
Next, split the result by space " "
After that, run through the array and remove anything that's on and before =, .*?=.
And now you have your result.

Complex Regex : how to don't match reserved word after //

I'm making a webcode editor, I'm working on the text markup so I wrote this regex : /\b(?:abstract|arguments|boolean|break|byte|case|catch|char|const|class|continue|debugger|default|delete|do|double|else|enum|eval|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|let|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|volatile|while|with|yield|alert|all|anchor|anchors|area|assign|blur|button|checkbox|clearInterval|clearTimeout|clientInformation|close|closed|confirm|constructor|crypto|decodeURI|decodeURIComponent|defaultStatus|document|element|elements|embed|embeds|encodeURI|encodeURIComponent|escape|event|fileUpload|focus|form|forms|frame|innerHeight|innerWidth|layer|layers|link|location|mimeTypes|navigate|navigator|frames|frameRate|hidden|history|image|images|offscreenBuffering|open|opener|option|outerHeight|outerWidth|packages|pageXOffset|pageYOffset|parent|parseFloat|parseInt|password|pkcs11|plugin|prompt|propertyIsEnum|radio|reset|screenX|screenY|scroll|secure|select|self|setInterval|setTimeout|status|submit|taint|text|textarea|top|unescape|untaint|window|onblur|onclick|onerror|onfocus|onkeydown|onkeypress|onkeyup|onmouseover|onload|onmouseup|onmousedown|onsubmit)\b(?=(?:[^"]*"[^"]*")*[^"]*$)(?=(?:[^']*'[^']*')*[^']*$)(?![^<]*>)(?![^\/*]*\*\/)/gm
This the group of reserved words
/\b(?:abstract|arguments|boolean|break|byte|case|catch|char|const|class|continue|debugger|default|delete|do|double|else|enum|eval|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|let|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|volatile|while|with|yield|alert|all|anchor|anchors|area|assign|blur|button|checkbox|clearInterval|clearTimeout|clientInformation|close|closed|confirm|constructor|crypto|decodeURI|decodeURIComponent|defaultStatus|document|element|elements|embed|embeds|encodeURI|encodeURIComponent|escape|event|fileUpload|focus|form|forms|frame|innerHeight|innerWidth|layer|layers|link|location|mimeTypes|navigate|navigator|frames|frameRate|hidden|history|image|images|offscreenBuffering|open|opener|option|outerHeight|outerWidth|packages|pageXOffset|pageYOffset|parent|parseFloat|parseInt|password|pkcs11|plugin|prompt|propertyIsEnum|radio|reset|screenX|screenY|scroll|secure|select|self|setInterval|setTimeout|status|submit|taint|text|textarea|top|unescape|untaint|window|onblur|onclick|onerror|onfocus|onkeydown|onkeypress|onkeyup|onmouseover|onload|onmouseup|onmousedown|onsubmit)\b
This skip markup if in double quotes
(?=(?:[^"]*"[^"]*")*[^"]*$)
This skip markup if in single quotes
(?=(?:[^']*'[^']*')*[^']*$)
This skip markup if in a tag <>
(?![^<]*>)
This skip markup if in a comment /* */
(?![^\/*]*\*\/)
Now I'm stuck on the last piece of cake, I need to skip markup if in a comment // [single line]
(?!\/\/[\w\s\'\"][^\n]*)|(?!\/\/)
Any suggestion?
My suggestion is not to use a regex for this kind of parsing job. Since you are building something in Javascript, you can use jison to convert a grammar that you design into a working javascript function that will parse text according to your grammar.
if you are curious this is my solution, please let me know if your eyes are bleeding or if it is a good solution :
//finding the string that I need to manipulate
regcomment2 =/(\/\/[\w\s\'\"][^\n]*)|(\/\/)/gm;
//this the loop to find and replace
var str = finale.match(regcomment2);
if(finale.match(regcomment2)){
str = str.toString();
var arr = str.split(",");
var arrcheck = str.split(",");
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
//writing right code
arr[i]= arr[i].replace(/(<.*?[^ok]>)/g,"");
console.log("Commento Split Dopo = " + arr[i]);
console.log("Commento Arr2 = " + arrcheck[i]);
//replace original code with right code
finale = finale.replace(arrcheck[i],arr[i]);
}

Overflowed text with html in another div

I want to have a text that overflows in another div, so I found and used this answer from another question at Stackoverflow.
The problem is that only plain text is displayed; links, bold/italics and paragraphs are ignored.
Here is the same jsfiddle from the answer, but with added html tags. How do i get to display them?
Code:
var currentCol = $('.col:first');
var text = currentCol.text();
currentCol.text('');
var wordArray=text.split(' ');
$.fn.hasOverflow = function() {
var div= document.getElementById( $(this).attr('id') );
return div.scrollHeight>div.clientHeight;
};
for ( var x = 0; x < wordArray.length; x++ ) {
var word = wordArray[x];
currentCol.append(word+' ');
if ( currentCol.hasOverflow() ) {
currentCol = currentCol.next('.col');
}
}
Any tips or advice will be appreciated :)
jQuery .text method returns only plain text. Try using .html instead.
Example:
var text = currentCol.html();
But if your tags contain any spaces (like <span class="some-class">) then the following line from your code will do a mess with your text
var wordArray=text.split(' ');
You might want to change it to
text = text.replace(/ (?![^<>]*>)/gi, '%^%');
var wordArray = text.split('%^%');
This is kind of workaround since you could iterate over each regex match and substring it on every space character but IMHO the above idea with %^% combination is much more simple. you can replace those 3 signs with anything you want. I just thought it is unique enough that won't be used in any other purpose.
Above regular expression is simplified and assumes that you don't use < and > signs in your text.
If you actually do I would recommend to replace them with < and > anyway.

Categories