AppendTo previous iteration (each) - javascript

I have the following code, which should split this string #266##271##295# into this
266
271
295
and append it to the same container where it came from: .groups
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(this);
});
});
My problem (i think) is the line $(html).appendTo(this);
i somehow need to add it to the previous each().
How can I do this. Or am I moving in the wrong direction with this code?

I think you made this way too complicated, just do this:
var str = $(this).html();
var parts = str.split("#");
var html = "";
for (var i = 0; i < parts.length; i++) {
html += '' + parts[i] + '';
}
$(this).append(html);

Something like this?
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
var target = $(this);
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(target);
});
});
I added the var target = $(this) outside your second loop as a reference that you can use inside your second loop.

You do need to be mindful of the leading and trailing #'s, but you can easily trim them while you split with a clever regex. When you use $.each to iterate over an array, the this reference no longer refers to your original context but to the current item. Constructing the item's markup and concatenating to a string which you insert outside of the loop will not only get around this, but also provide better performance since you will only be doing one DOM insertion.
$('.groups').each(function(){
var str = $(this).html();
str = str.replace(/^#+|#+$/g, ''); // trim leading and trailing #
var links = str.split("#");
var markup = '';
$.each(links, function(){
markup += '' + this + "\n";
});
$(markup).appendTo(this);
});

Related

Convert Text in an Input to show as href links using comma split in javascript/jquery

I am trying to split text with comma and show them as links. I am converting them as as text but don't know how to convert them into links. I am using this code.
$('.tags').keyup(function() {
var ref = $('.tags').val();
var str_array = ref.split(',');
for(var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
$('.tag').html($(this).val());
}
});
What I am Getting is
<span class="tag">hello, world</span>
what I want is
<span class="tag">hello, world</span>
This solution is done with pure JS. No need for JQuery
var tags = document.getElementById("tags");
tags.addEventListener("keyup", convert);
function convert() {
let tag = document.getElementById('tag');
tag.innerHTML = "";
let str = tags.value;
let res = str.split(",");
res.forEach(function(element, idx, array) {
let comma;
idx === array.length - 1 ? comma = '' : comma = ' , ';
let trimmedElement = element.trim();
tag.innerHTML += ''+ trimmedElement +''+ comma ;
});
}
<input type="text" id="tags">
<span id="tag"></span>
You can do as follows in jQuery:
var ref = $('.tags').val();
var str_array = ref.split(',');
var tagLinks = '';
for(var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
tagLinks += ''+str_array[i]+', ';
}
tagLinks = tagLinks.slice(0, -2);
$('.tag').html(tagLinks);
With jQuery:
// Element Selector
let selector = $(".tag");
// Get Text
let text = selector.text();
// Remove extra characters
text = text.replace(/[^a-zA-Z ]/ig, '');
// Convert my text to array
let tags = text.split(" ");
// Empty the element
selector.html('');
// Append Tags
tags.forEach(function(tag){
selector.append(`${tag} `)
});

Passing tab delimiter through via parameter not splitting string

My issue essentially is, I have a select box that has 2 options "Tab or CSV", those options meaning what to split a string on, my issue is when every I pass through "\t" as a parameter, it doesn't split on tabs. if I explictly type "\t" it splits the string but not if its being passed via a parameter.
I am trying to create a sql results to jira table chrome extention
The issues reside in the GetDelimiterType function and GenerateLine< first line.
I have no idea what is going on, if i check the value of delimerType it reads "\t" but doesn't split
$("#btn").click(function(){
var textToChange = $("#input").val().split("\n");
var topLineRow = $("#topRow").prop("checked");
var delimiterType = $("#delimiterSelect option:selected").val();
var jiraTable = "";
debugger;
if(topLineRow){
jiraTable += GenerateLine("||", textToChange[0], GetDelimiterType(delimiterType))
}
topLineRow = false;
var generatedString = "";
$.each(textToChange, function(index, value){
if(!topLineRow){
jiraTable += GenerateLine("|", textToChange[index],GetDelimiterType(delimiterType));
}
})
alert(jiraTable);
})
function GetDelimiterType(delimiterType){
debugger;
if(delimiterType == 0){
return ",";
}else if(delimiterType == 1){
return "\\t";
}
}
function GenerateLine(seperator, row, delimiter){
var rowArray = row.split(delimiter);
var rowText = "";
$.each(rowArray, function(index, value){
var isLastElement = index == rowArray.length -1;
value = value.replace(/\s/g,'');
if(index == 0){
rowText += seperator;
}
if(isLastElement){
rowText += value + seperator + "\n";
}else{
rowText += value + seperator;
}
});
return rowText;
}
.split(/.../)
.split() method can pass a regex literal as a delimiter.
/\b[^\S]+?\b|,\s/
\boundary meta-sequence denotes a non-spaced character next to a word character
[^\S]+? class ignores one or more non-whitespace characters
\b as above
|,\s OR a literal comma followed by a space
Demo
var row = `Mike, Alpha, Tango, Tango Zulu Echo Romeo 0 0 November Echo`;
var rowArray = row.split(/\b[^\S]+?\b|,\s/);
console.log(JSON.stringify(rowArray));

Remove HTML tags in script

I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.
For example: it replaces '<b>asserted</b>' with 'http://www.merriam-webster.com/dictionary/<b>asserted</b>'
Could you please tell me what to change in this code for it to change '<b>asserted</b>' to 'http://www.merriam-webster.com/dictionary/asserted'.
var content = document.getElementById("sentence").innerHTML;
var punctuationless = content.replace(/[.,\/#!$%\؟^?&\*;:{}=\-_`~()”“"]/g, "");
var mixedCase = punctuationless.replace(/\s{2,}/g);
var finalString = mixedCase.toLowerCase();
var words = (finalString).split(" ");
var punctuatedWords = (content).split(" ");
var processed = "";
for (i = 0; i < words.length; i++) {
processed += "<a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\">";
processed += punctuatedWords[i];
processed += "</a> ";
}
document.getElementById("sentence").innerHTML = processed;
This regex /<{1}[^<>]{1,}>{1}/g should replace any text in a string that is between two of these <> and the brackets themselves with a white space. This
var str = "<hi>How are you<hi><table><tr>I<tr><table>love cake<g>"
str = str.replace(/<{1}[^<>]{1,}>{1}/g," ")
document.writeln(str);
will give back " How are you I love cake".
If you paste this
var stripHTML = str.mixedCase(/<{1}[^<>]{1,}>{1}/g,"")
just below this
var mixedCase = punctuationless.replace(/\s{2,}/g);
and replace mixedCase with stripHTML in the line after, it will probably work
function stripAllHtml(str) {
if (!str || !str.length) return ''
str = str.replace(/<script.*?>.*?<\/script>/igm, '')
let tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
stripAllHtml('<a>test</a>')
This function will strip all the HTML and return only text.
Hopefully, this will work for you
if you need to remove HTML tags And HTML Entities You can use
const text = '<p>test content </p><p><strong>test bold</strong> </p>'
text.replace(/<[^>]*(>|$)| |‌|»|«|>/g, '');
the result will be "test content test bold"

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Set CSS of words enclosed in double quotes

This is a follow up question to my question about Setting the CSS of code if it contains a reserved word.
What I am trying to do: If some code has quotes or double quotes, I want to set the color of the font to red and bold. Ex. System.out.println( "Hello world" ); should set "Hello world" to red.
What's wrong: Despite my best efforts, I can't seem to get my control statements to work properly (at least I think that's the issue). It sets the first double quote and beyond to red, but when I tell it to stop when a word equals anyword" or anyword' it sets the rest of the code in the block to red.
HTML
<html>
<body>
<code id="java">
public static void main(String[] args)<br>
{
<pre> int i = 120; </pre><br>
<pre> // Displays a message in the console </pre>
<pre> // This is a test </pre>
<pre> System.out.println( "Hello Big World!" );</pre>
}
</code>
</body>
</html>
CSS
.quotes
{
font-weight: bold;
color: #E01B1B;
}
jQuery
$(document).ready(function() {
var code = $("#java").html(); // Get the code
var split = code.split(' '); // Split up each element
var chkQ = 0; // Check for quotes
var chkC = 0; // Check until end of comment line
// Set the CSS of reserved words, digits, strings, and comments
for (var j = 0; j < split.length; j++) {
// Check to see if chkQ is set to true
if (chkQ == 1) {
// If the element matches (anyword") or (anyword'), then set
// flag to false and continue checking the rest of the code.
// Else, continue setting the CSS to .quotes
if (split[j].match(/."/) || split[j].match(/.'/)) {
split[j] = '<span class="quotes">' + split[j] + '</span>';
chkQ = 0;
} else {
split[j] = '<span class="quotes">' + split[j] + '</span>';
}
}
...
} else if (chkQ == 0 && chkC == 0) {
...
// If the element matches a ("anyword) or ('anyword)...
} else if (split[j].match(/"./) || split[j].match(/'./)) {
split[j] = '<span class="quotes">' + split[j] + '</span>';
chkQ = 1;
} ...
}
}
// Join all the split up elements back together!
$("#java").html(split.join(' '));
});
Question: Is this just simply an issue with my regex, control blocks or something completely different?
Why split the string up when you can perform a simple global regex find and replace:
<script type="text/javascript">
$(document).ready(function(){
//cache the element
el = $('#java');
//get the HTML contained within the cached element
code = el.html();
//return the code having executed the replace method, regex explained:
/*
([^\w]{1}) -> look for a single character that is not an alpha character
(["']) -> then look for either a single quote or double quote
(.*?) -> then look any character, but don't be greedy
(\2) -> then look for what was found in the second group - " or '
([^\w]{1}) -> and finally look for a single character that is not an alpha character
*/
code = code.replace(/([^\w]{1})(["'])(.*?)(\2)([^\w]{1})/gm,
//execute an anonymous callback, passing in the result for every match found
function(match, $1, $2, $3, $4, $5, offset, original) {
//construct the replacement
str = $1 + '<span class="quotes">' + $2 + $3 + $4 + '</span>' + $5;
//return the replacement
return str;
});
//replace the existing HTML within the cached element
el.html(code);
});
</script>
Edit: Just updated it to accommodate nested quotes.
I don't know all your requirements, but it seems that your single quote could get a bit complicated.
I've set up a demonstration that works (updated link to include nested quotes).
I do not guarantee it is bug free. It does the replacement in two stages, first for double quotes, then for single, trying to weed out potential apostrophes (note in the code below the filters for apostrophes are based off common following letters--not sure how many you might practically need, if any).
Javascript
$(document).ready(function() {
var code = $("#java").html(); // Get the code
var split = code.split('\"'); // Split up each element at the "
// Set the CSS of reserved words, digits, strings, and comments
for (var j = 0; j < split.length - 1; j++) {
if (j%2 == 0) { //if first, add beginning
split[j] = split[j] + '<span class="quotes">"';
} else {//if second, add ending
split[j] = split[j] + '"</span>';
}
}
// Join all the split up elements back together!
$("#java").html(split.join(""));
code = $("#java").html(); // Get the code
split = code.split('\''); // Split up each element at the '
var openQ = 1;
var sub1;
var sub2;
for (var j = 0; j < split.length - 1; j++) {
sub1 = split[j+1].substr(0,2); //checking for a contraction of 's
sub2 = split[j+1].substr(0,3); //checking for a contraction of 'll
if(sub1 != "s " && sub2 != "ll ") {
if (openQ) { //if first, add beginning
split[j] = split[j] + '<span class="quotes">\'';
openQ = 0;
} else {//if second, add ending
split[j] = split[j] + '\'</span>';
openQ = 1;
}
}
else {//add apostrophe back
split[j] = split[j] + '\'';
}
}
$("#java").html(split.join(""));
});
Here's a pure JavaScript version:
id= id of element with quotes
classid= class to add to the quotes
function quotes(id,classid) {
var code = document.getElementById(id).innerHTML;
var split = code.split('\"');
for (var j = 0; j < split.length - 1; j++) {
if (j%2 == 0) {
split[j] = split[j] + '<span class='+classid+'>"';
} else {
split[j] = split[j] + '"</span>';
}
}
document.getElementById(id).innerHTML = split.join("");
code = document.getElementById(id).innerHTML;
split = code.split('\'');
var openQ = 1;
var sub1;
var sub2;
for (var j = 0; j < split.length - 1; j++) {
sub1 = split[j+1].substr(0,2);
sub2 = split[j+1].substr(0,3);
if(sub1 != "s " && sub2 != "ll ") {
if (openQ) {
split[j] = split[j] + '<span class='+classid+'>\'';
openQ = 0;
} else {
split[j] = split[j] + '\'</span>';
openQ = 1;
}
}
else {
split[j] = split[j] + '\'';
}
}
document.getElementById(id).innerHTML = split.join("");
}
String.prototype.Text2Html = function (){
var div = document.createElement('div');
div.appendChild(document.createTextNode(this))
encoded=div.innerHTML;
div.remove();
return encoded
}
String.prototype.colorTheQuotes = function(){
var re = /(?:<span style=|)(?:(?:"[^"]*")|(?:'[^']*'))/gm,
text = this.Text2Html(),
output = text,
tour = 0,
slen = 27;
while ((match = re.exec(text)) != null) {
if(match[0].startsWith("<span")) continue
output=output.slice(0,match.index+tour*slen)+'<span class="quote">'+output.slice(match.index+tour*slen,match.index+match[0].length+tour*slen)+"</span>"+output.slice(match.index+match[0].length+tour*slen);tour++
}
return output
}
element=document.getElementById("color")
document.addEventListener("readystatechange",(e)=>{
element.innerHTML=element.innerText.colorTheQuotes();
})
.quote{
color: red;
}
<span>System.out.println( "Hello world" );</span><br>
<span id="color">System.out.println( "Hello world" );</span>

Categories

Resources