I would like to know how to create a for-loop with text content that I cannot modify. The text I am given looks like so:
<start>John</stop><start>Billy</stop>
I have two texts, John and Billy that are each surrounded by start and stop tags. What I would like to do is add these names without the tags to my HTML. My incomplete code looks something like:
var mytext = "<start>John</stop><start>Billy</stop>";
var count = (mytext.match(/<start>/g) || []).length;
for (i = 0; i < count; i++){
something.innerHTML += eachname;
}
Would like to know how to complete this.
Try with /<[^>]*>/gi like the following:
Please Note: Since the output is plain text it is better to use textContent instead of innerHTML.
var mytext = "<start>John</stop><start>Billy</stop>";
function get_content() {
//var html = document.getElementById("txtInput").innerHTML;
document.getElementById("txt").textContent = mytext.replace(/<[^>]*>/gi, "");
}
get_content();
<div id="txt">
</div>
You can use the following javascript example for your solution.
var mytext = "<start>John</stop><start>Billy</stop>";
mytext = mytext.replace(/<\/?start[^>]*>/ig, ""); //Replace all <start> with blank
console.log(mytext.split(/<\/?stop[^>]*>/ig)); //Split by <stop> this may return an array ...
Related
I have a long String containing a HTML document. I want to delete all the href Tags but keep the text. The following example:
Some text example 1</p> some example 2text
should become:
Some text example 1 </p> some example 2 text
The solution I found is to get all the textes, and then try to iterate again through the text and replace the tag number n with the text number n.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
var texts = [].slice.call(a).map(function(val){
return val.innerHTML;
});
alert(texts);
// TODO ieterate and replace occurence n with texts[n]
Is there a besser way to do this?
After first line write following code
a_string = a_string.replace(/(<a.*?>)/g,'').replace(/<\/a>/g,' ');
You can use the following Regex:
var regex = /(<\s*a([^>]+)>|<\/\s*a\s*>)/ig;
var str = 'Some text example 1</p> some example 2text';
str.replace(regex, ""); //Some text example 1</p> some example 2text
Try below regex:
var a_txt = a_string.replace(/<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>/g,"").replace(/<\/a>/g," ");
Your solution of query-selecting all a-tags isn't actually too bad. Instead of getting the text with map you could just iterate over the list and replace each element with its content. No need for regular expressions:
el.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
also, instead of "parsing" your html by putting it into a p-element, you could use a DomParser:
var parser = new DOMParser();
var doc = parser.parseFromString(a_string, "text/html");
doc.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
as stated in some answer above, your code isn't bad. I avoid the use of regular expression when not necessary.
To finish your code, you neeed to iterate through all A{ELEMENTS}. I am typing from mobile phone. Let me know if you hit an error. Thanks.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
for( var t = a.length - 1; t >=0 ; t-- ){
for(var c = a[t].childNodes.length - 1; c >= 0; c-- ){
if( a[t].nextSibling ){
document.insertBefore( a[t].childNodes[c], a[t].nextSibling );
} else {
a[t].parentNode.appendChild( a[t].childNodes[c]);
}
}
a[t].remove();
}
Am trying to replace a particular string from all lines using javascript. Here is sample
www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=PYOQLPW6ewQ&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=ejRmaOHs1rk&index=39&list=PLB03EA9545DD188C3
I want to replace the 11 characters after '=' how can I do it with a variable
like var= 'hello123456'
so output will be
www.youtube.com/watch?v=hello123456&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=39&list=PLB03EA9545DD188C3
Here is regex solution, see the snippet below
document.addEventListener("DOMContentLoaded", function(){
var link = "www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var value = "hello123456";
link = link.replace(/\?v=(.*)\&index/g, "?v="+value+"&index")
document.getElementById("id").innerHTML = link
});
Input link:
<div>www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3</div>
<br>
<br>
Output link:
<div id="id"></div>
Please check the below code
var youstr="www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var start=youstr.indexOf("=");
var end=start+11;
var replaceStr=youstr.slice(start,start+11);
youstr=youstr.replace(replaceStr,"ReplaceString");
This is pretty straightforward solution, without any fanciness so you could easy understand what's happening.
var originalStr = 'www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3';
var textToReplaceWith = 'hello123456';
var newStr = '';
// get index where unwanted text starts
var index = originalStr.indexOf('v=') + 2;
newStr = originalStr.substring(0, index); //take part just before the unnecessary text
newStr += textToReplaceWith; //add string you want
newStr += originalStr.substring(index + 11, originalStr.length) // take text part after unwanted text
I have a HTML textarea with a string split across multiple lines. for example
cat
dog
horse
What I'm then trying to do is insert these strings into a html table. the HTML table ( I'm using jquery.datatables) seems to ignore the newlines. So what I'm
<textarea id='txttest' name="texttest" ></textarea>
I've tried replacing the text like so but both of these do not work.
var res = $("textarea#txttest").val().replace(/\/n/,"<br>");
or
var res = $("textarea#txttest").val().replace(/
/,"<br>");
I then insert the result into my datatable
$('table#table_flows').dataTable().fnAddData( [
res ] );
but the newlines are not being replaced by < br >
How do I do this?
thank you.
You have an extra slash in your .replace and you need to add a g to make it a global replace rather than just the first occurence.
Try
var res = $("textarea#txttest").val().replace(/\n/g,"<br>");
Example
Try this: split into an array using NewLine as separator, then rejoin the string array with <br />
var res = $("textarea#txttest").val().split("\n").join('<br />');
$('table#table_flows').dataTable().fnAddData( [ res ] );
Check the result here
I didn't try any example using replace(), like you were just doing. Instead, I put together an example using split() that splits the value at the \n character.
http://jsfiddle.net/TY22g/
var cell = document.getElementsByTagName("td")[0];
var textarea = document.getElementsByTagName("textarea")[0];
textarea.addEventListener("change", function() {
var array = textarea.value.split("\n");
var i = 0, length = array.length;
for (i; i < length; i++) {
cell.innerHTML += array[i] + "<br/>";
}
});
I'm trying to convert characters like < and > into < and > etc.
User input is taken from a text box, and then copied into a DIV called changer.
here's my code:
function updateChanger() {
var message = document.getElementById('like').value;
message = convertHTML(message);
document.getElementById('changer').innerHTML = message;
}
function convertHTML(input)
{
input = input.replace('<', '<');
input = input.replace('>', '>');
return input;
}
But it doesn't seem to replace >, only <. Also tried like this:
input = input.replace('<', '<').replace('>', '>');
But I get the same result.
Can anyone point out what I'm doing wrong here? Cheers.
A more robust way to do this is to create an HTML text node; that way all of the other potentially invalid content (there's more than just < and >) is converted. For example:
var message = document.getElementById('like').value;
document.getElementById('changer').appendChild(document.createTextNode(message));
UPDATE
You mentioned that your event was firing upon each key press. If that's what's triggering this code, you'll want to remove what was previously in the div before appending the text. An easy way to do that is like this:
var message = document.getElementById('like').value;
var changer = document.getElementById('changer');
changer.innerHTML = '';
changer.appendChild(document.createTextNode(message));
Try something like this:
function convertHTML(input)
{
input = input.replace(/>/g, '>');
input = input.replace(/</g, '<');
return input;
}
replace only replaces the first occurrence of > or < in the string, in order to replace all occurrences of < or >, use regular expressions with the g param to ensure the entire string is searched for all occurrences of the values.
I have a string containing HTML loaded from another page, how do I extract the background property from it's body tag using Javascript?
The body tag in the string looks like this:
<body onload='init();' background='storage/images/jsb_background.jpg' link='#000000' vlink='#000000' alink='#000000' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>
Thanks!
I patched together a regex to do this, which will search the data string variable (containing the HTML) for the background attribute of the body tag. The regex is stolen from here and modified a bit. I'm still new to regex, so I guess it can be done more fluently, but it still gets the job done
var data = /* your html */;
var regex = /body.*background=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/;
var result = regex.exec(data);
if (result.length > 1) {
var background = result[1];
alert(background);
}
else {
//no match
}
This is my answer as I understand your problem (given the limited details and no code example)...
This is also assuming that your HTML string is valid html...
var html = yourString;
var background = "";
background = $(html).find("body").attr("background");
If you aren't actually appending your HTML string to the DOM there may not be a nice and easy jQuery way to do this. You may have to parse out the background attribute by hand.
var html = yourString;
var charStart = html.indexOf("<body");
var charEnd = html.indexOf(">", charStart);
var bodyTag = html.substring(charStart,charEnd+1);
charStart = bodyTag.indexOf("background='")+12;
charEnd = bodyTag.indexOf("'",charStart+13);
var background = bodyTag.substring(charStart,charEnd);