Am trying to use regex to manipulate the following string
hello.jpg|world.jpg
to
<li>http://example.com/hello.jpg</li>
<li>http://example.com/world.jpg</li>
Any pointers?
split your input and add it to your html DOM
<ul id="list">
</ul>
<script>
var html = "hello.jpg|world.jpg".split("|");
for (var vl in html) {
var li = document.createElement("li");
li.innerHTML = "http://example.com/" + html[vl];
document.getElementById("list").appendChild(li);
}
</script>
Assuming you want the output to be a string of HTML rather than actual DOM nodes you've got a choice between a RegExp or using split:
var str = 'hello.jpg|world.jpg|globe.jpg';
// Using RegExp
var str1 = str.replace(/([^|]+)\|?/g, '<li>http://example.com/$1</li>');
// Using split/map/join with ES6
var str2 = str.split('|').map(img => `<li>http://example.com/${img}</li>`).join('');
// Using split/map/join old school
var str3 = str.split('|').map(function(img) {
return '<li>http://example.com/' + img + '</li>';
}).join('');
console.log(str1);
console.log(str2);
console.log(str3);
Note that none of these examples HTML encodes the image name. If that's a concern you couldn't use the RegExp approach but the other two could easily be adapted.
If you wanted to create the actual DOM nodes then it might be easiest to use one of the approaches above to generate a string and then just set the innerHTML of your <ul>. If you wanted to cut out the middleman and go straight to the DOM you could try something like this:
var ul = document.getElementById('list');
var str = 'hello.jpg|world.jpg|globe.jpg';
str.split('|').forEach(function(img) {
var li = document.createElement('li');
li.innerText = 'http://example.com/' + img;
ul.appendChild(li);
});
<ul id="list"></ul>
By using innerText the HTML encoding has been accounted for.
Whilst you wanted to use regex, you can also use split()
The split() function takes in a particular character you want to split a string by and stores it as an array. You can then use each item in that array to do what ever with... In this instance, I appended each one into a new variable it and inserted it into a div.
var str = "hello.jpg|world.jpg";
var res = str.split("|");
var html = "<li>http://example.com/"+res[0]+"</li><li>http://example.com/"+res[1]+"</li>";
document.getElementById("foo").innerHTML = html;
<div id="foo"></div>
Simply match the everything but the pipe (|)
var myString = 'hello.jpg|world.jpg';
var matches = myString.match(/[^|]{1,}/g);
Then do whatever you want with the matched items, like add them to the DOM.
var container = document.getElementById('container');
for(var i = 0; i < matches.length; i++) {
var li = document.createElement('li');
li.innerHTML = matches[i];
container.appendChild(li);
}
Related
I am new in JavaScript. I have 3 numbers with 10 digits in a <p> tag, and I would like to select and convert them to a link. I was able to get the numbers and convert them to link, but I am getting all 3 numbers at the same time as one link, it would be great if I can get some help, Thank you
Here is my code:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '"'+text+'"');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>
You can capture certain expressions in regex. Then you can get value from that group by using $ and a group number. There's only one group so in this case there'll be $1;
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$1";
var rgx = /(\d{10})/g; // () wraps an expression in a group
var text = str.match(rgx);
var res = str.replace(rgx, '$1');
document.querySelector("p").innerHTML = res;
}
More about capturing groups: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
Edit: I found even a simpler way - if you want to refer to the whole expression you don't need to create a group. To insert matched value you can use $&:
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$&";
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '$&');
document.querySelector("p").innerHTML = res;
}
str.match(rgx);
returns an array of matching strings. If you want to use only on item of the array, you can reference to the index (like text[0]) or you can i.e. loop over the array with text.forEach
or you can map over it and generate links like this:
let links = text.map((string) => { return `www.yourlink.com/${string}`})
in your replace statement use text instead of rgx
var res = str.replace(text, '"'+text+'"');
that way you only replace the instance of the matched text instead of all the rgx matches
EDIT
this should do it
function myFunction() {
var str = document.querySelector("p").innerHTML;
var rgx = /\d{10}/g;
var text = str.match(rgx);
for (i=0; i<text.length; i++) {
var link = 'https://www.google.com/search?q='+text[i];
str = str.replace(text[i], '"'+text[i]+'"');
}
document.querySelector("p").innerHTML = str;
}
myFunction();
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();
}
Given this HTML as a string "html", how can I split it into an array where each header <h marks the start of an element?
Begin with this:
<h1>A</h1>
<h2>B</h2>
<p>Foobar</p>
<h3>C</h3>
Result:
["<h1>A</h1>", "<h2>B</h2><p>Foobar</p>", "<h3>C</h3>"]
What I've tried:
I wanted to use Array.split() with a regex, but the result splits each <h into its own element. I need to figure out how to capture from the start of one <h until the next <h. Then include the first one but exclude the second one.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
var foo = html.split(/(<h)/);
Edit: Regex is not a requirement in anyway, it's just the only solution that I thought would work for generally splitting HTML strings in this way.
In your example you can use:
/
<h // Match literal <h
(.) // Match any character and save in a group
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/h // Match literal </h
\1 // Match what previous grouped in (.)
> // Match literal >
/g
var str = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>'
str.match(/<h(.)>.*?<\/h\1>/g); // ["<h1>A</h1>", "<h2>B</h2>", "<h3>C</h3>"]
But please don't parse HTML with regexp, read RegEx match open tags except XHTML self-contained tags
From the comments to the question, this seems to be the task:
I'm taking dynamic markdown that I'm scraping from GitHub. Then I want to render it to HTML, but wrap every title element in a ReactJS <WayPoint> component.
The following is a completely library-agnostic, DOM-API based solution.
function waypointify(html) {
var div = document.createElement("div"), nodes;
// parse HTML and convert into an array (instead of NodeList)
div.innerHTML = html;
nodes = [].slice.call(div.childNodes);
// add <waypoint> elements and distribute nodes by headings
div.innerHTML = "";
nodes.forEach(function (node) {
if (!div.lastChild || /^h[1-6]$/i.test(node.nodeName)) {
div.appendChild( document.createElement("waypoint") );
}
div.lastChild.appendChild(node);
});
return div.innerHTML;
}
Doing the same in a modern library with less lines of code is absolutely possible, see it as a challenge.
This is what it produces with your sample input:
<waypoint><h1>A</h1></waypoint>
<waypoint><h2>B</h2><p>Foobar</p></waypoint>
<waypoint><h3>C</h3></waypoint>
I'm sure someone could reduce the for loop to put the angle brackets back in but this is how I'd do it.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
//split on ><
var arr = html.split(/></g);
//split removes the >< so we need to determine where to put them back in.
for(var i = 0; i < arr.length; i++){
if(arr[i].substring(0, 1) != '<'){
arr[i] = '<' + arr[i];
}
if(arr[i].slice(-1) != '>'){
arr[i] = arr[i] + '>';
}
}
Additionally, we could actually remove the first and last bracket, do the split and then replace the angle brackets to the whole thing.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
//remove first and last characters
html = html.substring(1, html.length-1);
//do the split on ><
var arr = html.split(/></g);
//add the brackets back in
for(var i = 0; i < arr.length; i++){
arr[i] = '<' + arr[i] + '>';
}
Oh, of course this will fail with elements that have no content.
Hi I used this function to convert html String Dom in array
static getArrayTagsHtmlString(str){
let htmlSplit = str.split(">")
let arrayElements = []
let nodeElement =""
htmlSplit.forEach((element)=>{
if (element.includes("<")) {
nodeElement = element+">"
}else{
nodeElement = element
}
arrayElements.push(nodeElement)
})
return arrayElements
}
Happy code
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 have a simple string e.g.
var s = "<p>Hello World!</p><p>By Mars</p>";
How do I convert s to a jQuery object? My objective is to remove the <p>s and </p>s. I could have done this using regex, but that's rather not recommended.
In the simplest form (if I am understanding correctly):
var s = "<p>Hello World!</p><p>By Mars</p>";
var o = $(s);
var text = o.text();
Or you could use a conditional selector with a search context:
// load string as object, wrapped in an outer container to use for search context
var o = $("<div><p>Hello World!</p><p>By Mars</p></div>");
// sets the context to only look within o; otherwise, this will return all P tags
var tags = $("P", o);
tags.each(function(){
var tag = $(this); // get a jQuery object for the tag
// do something with the contents of the tag
});
If you are parsing large amounts of HTML (for example, interpreting the results of a screen scrape), use a server-side HTML parsing library, not jQuery (tons of posts on here about HTML parsing).
To get all the strings there use
var s = "<p>Hello World!</p><p>By Mars</p>";
var result = "";
$.each($(s), function(i){
result += " " + $(this).html();
});
if you don't want regex, why don't u just:
var s = "<p>Hello World!</p><p>By Mars</p>";
s = s.replace('<p>', '').replace('</p>', '');