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>
Related
I am trying to get a text and add an onclick event with a function on each word of the text. It works perfectly with some sentences, but it doesn't with others. When it doesn't work, part of the html tags are displayed on the page. I noticed that it never works when there are repeated words or when I use the words "a" or "an", but I don't know why.
Here is how I am doing it:
I enter the text in the page using a textarea tag.
<textarea id="text-input"></textarea>
Then I grab the text, split it into an array with all the words and add an onclick event with a function to each word.
function addLink(){
let text = document.getElementById('text-input').value
const words = text.match(/\w+/g)
words.forEach(word => {
text = text.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span>`)
})
document.getElementById('result').innerHTML = text
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail')
result = `<h3>${word}</h3>`
return wordDetail.innerHTML = result
}
The "addLink" function is called when I submit the text.
<button onclick="addLink()">Submit</button>
If I enter, for example, "My brother is engineer". It works perfectly. The onclick event is added to all the words.
But if I enter "My brother is an engineer", this is the result:
"an onclick=showWordDetail('My')>My brother is an engineer."
I console.log'ed the array of all my attempts and the text is split correctly. So I have no idea why sometimes it works, but sometimes it doesn't.
I think this is what you want. It avoids some of the problems of the answers that just split at spaces.
const wordDetail = document.getElementById('word-detail'),
input = document.getElementById('text-input'),
result = document.getElementById('result');
function addLink() {
result.innerHTML = input.value.replace(/\w+/g,`<span onclick="showWordDetail('$&')">$&</span>`)
}
function showWordDetail(word) {
wordDetail.innerHTML = `<h3>${word}</h3>`
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<div id="result"></div>
<hr/>
<div id="word-detail"></div>
My brother is an engineer
So this includes the word an.
Now look at what you replaced My with:
<span onclick=showWordDetail('My')>My</span>
So when you get to an what is going to be replaced?
What is the first place that the sequence of characters an attpears?
The an of the <span>
You would probably be better off with something like:
const html = words.map(word => `<span ....>${word}</span>`).join(" ");
document.getElementById('result').innerHTML = html
where you build a new set of HTML piece by piece instead of trying to replace the old content piece by piece.
Use split() instead, with separator space and replace every word, after replace it, add it to text value like that:
function addLink(){
let text = document.getElementById('text-input').value;
const words = text.split(" ");
text = "";
words.forEach(word => {
text += word.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span> `);
});
document.getElementById('result').innerHTML = text;
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail');
wordDetail.innerHTML = `<h3>${word}</h3>`;
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<p id="result"></p>
<div id="word-detail"></div>
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)
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
<script>
var chars = 55;
if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>
... The output would be:
This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.
You can try this
var chars = 55;
if ($('#mytext').text().length > chars){
var text = $('#mytext').text(); // div text
var chars_text = text.substring(0, chars); // chars text
var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span
$('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
Note: if you just need to replace the next one dot after chars you can
use '.' instead of /\./g
this way : With JQUERY Substring
<p>
this is test string with jquery . test 1 2 3 4 45 5 . test test test
</p>
<b></b>
<script>
var a = $('p').text();
var _output = '';
var _allow_index = 40;
if (a.length > _allow_index)
{
var x = a.split('.');
for(var i=0; i<x.length; i++)
{ if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
}
else { _output = a; }
$('b').html(_output + '<br>'+a.substr(_output.length,a.length));
</script>
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages.
Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text().
However here is a way for the given case:
var container = $('#mytext');
var length = 55;
var insert = '<br/>';
var text = container.text().trim(); // text() or html()
var dotPosAfterLength = text.indexOf(".", length);
if (dotPosAfterLength != -1) {
container.html(
text.substring(0, dotPosAfterLength+1)
+insert
+text.substring(dotPosAfterLength+1)
);
}
You just need to add this property in CSS.
<div id="mytext">
This is just a example. I need to find a solution.
I will appreciate any help. Thank you.
</div>
<style>
div#mytext{
word-wrap: break-word;
}
</style>
I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here
I have a HTML string ( not DOM element ) like :
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>
I need to append a <span class="spellerror"></span> to the words that have problem and that too only the Textual contents need to be checked and appended .
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image"><span class="spellerror"> Randomz </span> is the name of the image</img>
My problem is that this is a mix of HTML and regex . Is it possible:
To make this some kind of a DOM element and then work on it ?
Or is there a regex way to achieve this.
I dont want to touch the attributes and if I modify Text contents , how do I publish it back ...because I need some HTML inserted there .
I dont love this solution, but it works:
'<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>'
.match(/<[^>]+>|[^<]+|<\/[^>]+>/g)
.map(function (text, index) {
if (index === 1) {
return text.replace(/(Randomz)/, '<span class="spellerror">$1</span>');
} else {
return text;
}
})
.join('');
The regex splits into opening tag, innerText, closing tag.
Then iterates on all members, if its the innerText, it replaces with desired text
Then joins.
Im stil trying to think of something less round-about but thats all i got
Use some form of templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
;
function replacer(a){
var aa = Number(a.substr(1))-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer);
};
var thestring = [ '<p>This is a sample dataa</p><img src="Randomz"'
,' alt="Randomz Image">$1Randomz$2 '
,'is the name of the image</img>'].join('')
,nwString = theString.template('<span class="spellerror">','</span>');