I'm looking to convert a string of content into a list separated by ",".
The content should be inserted in a textbox by the user.
This is my html:
<textarea id="csv_text" onkeyup=""></textarea>
<input onclick="convert_to_list()" value="Konvertera" type="button"/>
</fieldset>
</form>
<div id="converted_list">
And this is the Javascript that I try to make work, but I can't get my head around it:
function convert_to_list() {
var inputText= document.getElementById("csv_text").value;
var inputText = input.split(",");
document.getElementById("converted_list").innerHTML;
}
What am I doing wrong!?
You need to iterate the created array and create a new div with the list item as content.
function convert_to_list() {
var inputText= document.getElementById("csv_text").value;
var splittedText = inputText.split(",");
var anchor = document.getElementById("converted_list");
splittedText.forEach(text => {
var listItem = document.createElement("div")
listItem.innerText = text
anchor.appendChild(listItem)
})
}
In Java (since question is also marked with Java tag):
From text to list1:
List<String> convertToList(String text) {
return Arrays.asList(text.split(",",-1));
}
From list to text:
String convertToText(List<String> list) {
return String.join(",", list);
}
1: structure (size) of returned list cannot be changed - add new ArrayList<>(...) to create a fully modifiable list
Related
I have some node list, and I am trying to get some values from this list.
It works fine but I can't append the values in new lines and everything rendered together.
<div class="newinsert"></div>
<script>
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML} `
indiv.append(html)
})
</script>
I tried adding <br> on html var but it just prints <br> with ""
\n doesn't work too
Thanks in advance.
EDIT: ok fixed it by
indiv.insertAdjacentHTML('beforeend', ${html} < br >)
append function receive string or HTMLNode element (more info)
but if your purpose is just to learn,you can simply replace InnerHtml content with your Html;
or concatenate it to the current content;
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML}<br> `
indiv.innerHTML = html
//or
indiv.innerHTML = indiv.innerHTML+html // if you effectly want to append conent to current dev content
})
<div class="newinsert"></div>
I want to extract html codes from a textarea value but failed.
I want to detect and replace images with textarea value.
Below is an example of what I want to do.
TEXTAREA
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
The code below is an example of what I want to do, I know it's wrong.
var editor_images = $('.editor').val().find('img');
editor_images.each(function(key, value) {
$(this).attr('src','example');
});
If you want to replace multiple attributes or tags, then your question may be too broad. However, the example below gives you an idea of how to replace an image attribute within the textarea:
function replaceValueOfTextArea(searchAttr, replaceAttr, value) {
const editor = document.querySelector('.editor');
const imgs = editor.value.match(/<img[a-zA-Z0-9="' ]+>/g);
let textAreaNewValue = '';
for (let img of imgs) {
const regMatch = new RegExp(`(?<!img)${searchAttr}`, "gi");
const match = img.match(regMatch);
if (match) {
const regAttr = new RegExp(`${searchAttr}=["|'][^"|']+["|']`, "gi");
textAreaNewValue += img.replace(regAttr, `${replaceAttr}="${value}"`);
} else {
textAreaNewValue += img;
}
}
editor.value = String(textAreaNewValue);
}
replaceValueOfTextArea('src', 'src', 'https://example.com');
<textarea class="editor"><img src="x1"><img alt="x2"></textarea>
You can use jQuery's $.parseHTML() to parse an HTML string into DOM nodes. Then you can use this method to turn them back into HTML before reinserting them in your <textarea>:
// Get contents of editor as HTML and parse into individual <img> nodes:
let nodes = $.parseHTML( $('.editor').val() )
// Map through <img> nodes and change src attribute, and return as HTML text:
let html = nodes.map(function(node){
$(node).attr('src', 'example')
return $('<div>').append($(node).clone()).html();
})
// Insert HTML text back into editor:
$('.editor').html( html.join('') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)
I have the following innerHTML in element id "word":
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span
I would like to create a function (wordReverter) that removes all of the tags, leaving in the above example, only the word "hello".
Any help would be greatly appreciated, thank you!
function wordReverter() {
var word = document.getElementById("word").innerHTML;
//var rejoinedWord = rejoined word with <span> tags removed
document.getElementById("word").innerHTML = rejoinedWord;
}
Get the innerText and use it as a new innerHtml like below
(function wordReverter() {
var word = document.getElementById("word").innerText;
document.getElementById("word").innerHTML = word;
})()
<div id="word">
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>
</div>
If you have the containing element, you can target it and retrieve it's textContent, otherwise, you can select all the elements of interest and retrieve their content as below:
function wordReverter() {
let letters = document.querySelectorAll('.white,.green')
return Array.from(letters).map(l=>l.textContent).join('')
}
console.log(wordReverter())
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>
I am adding some HTML tags using JavaScript like this:
function createTag(text) {
if (text != '') {
text = text.replace(',', '');
if (/^\s+$/.test(text) == false) {
var tag = $('<div class="tags">' + text + '<a class="delete">X</a></div>');
tag.insertBefore($('input.tag_list'), $('input.tag_list'));
$('input.tag_list').val('');
}
}
I want to get the values in the <div class="tags"> tags from all over the page. How can I do it?
Also how can I restrict the number of dynamically created tags of these types?
Select the tags and use the map() function to return an array. Within the function supplied to map() remove the a from a cloned tag.
var tags = $(".tags").map(function(){
var clone = $(this).clone();
$(clone).find("a").remove("a");
return clone.text();
});
JS Fiddle: http://jsfiddle.net/ELxW4/
You could make life somewhat easier by wrapping the values in span tags:
<div class="tags"><span>javascript</span><a class="delete">X</a></div>
<div class="tags"><span>java</span><a class="delete">X</a></div>
<div class="tags"><span>jquery</span><a class="delete">X</a></div>
Then get the tags using:
var tags = $(".tags").map(function(){
return $(this).find("span").text();
});