I got some html formatted in the following way:
[Title|<a class="external" href="http://test.com">http://test.com</a>]
From these texts I'd like to create links using "Title" as the text and "http://test.com" as link. How can I best do this in prototype?
Pure RegExp:
var ProperLink=WierdString.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/,'$2$1</a>')
in the context you provided:
function convert(id){
$(id).innerHTML=$(id).innerHTML.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/g,'$2$1</a>');
}
convert('testdiv');
Here is a regex that will retain the original attributes of the anchor tag while doing the replacement:
var link = "[Title|<a class=\"external\" href=\"http://test.com\">http://test.com</a>]";
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/;
link.replace(pattern, "$2$1$3"));
The output is:
<a class="external" href="http://test.com">Title</a>
Without prototype: http://jsfiddle.net/JFC72/ , you can use prototype to make it simpler.
var myStr = "[THIS IS TITLE|http://test.com]";
document.getElementById('testdiv').innerHTML = getLink(myStr);
function getLink(myStr)
{
var splitted = myStr.split("|http");
var title = splitted[0].substring(1);
var href = splitted[1].substring(0,splitted[1].length-1);
return "<a href='http" + href + "'>" + title + "</a>";
}
var dummyDiv = document.createElement('div');
dummyDiv.innerHTML = '[Title|<a class="external ...';
var parts = dummyDiv.innerText.slice(1, -1).split('|');
// parts[0] is the text, parts[1] is the URL
Related
Need to remove specific HTML tag span with class "notranslate", The following solution is removing all HTML tag from my text.
My expected result is: Deleted String: Adding string: Idea No.<p>d</p> value Details
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
console.log('Deleted String: ' + addStr.replace(new RegExp(/<\/?[\w\s="/.':;#-\/\?]+>/gi), ''));
If you really want to do it with a RegEx, you can use the below to strip any HTML span element which has the notranslate class. It takes into account the fact that you can have other properties on the element and multiple class names. As long as there is a <span> with class notranslate, it will strip the HTML tag and keep the content.
/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/
Working snippet:
let str1 = 'I want <span class="notranslate" data-xyz="whatever">this</span> to be removed.';
console.log('original:', str1);
console.log('modified:', str1.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/, "$1"));
let str2 = 'I want <span class="whatever notranslate another-class" data-xyz="whatever">this</span> to be removed.';
console.log('original:', str2);
console.log('modified:', str2.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/, "$1"));
If you can have multiple occurrences of that tag in the same string, you can add the g (global) flag.
/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/g
let str1 = 'I want <span class="notranslate" data-xyz="whatever">this</span> but <span class="notranslate" data-xyz="whatever">also this</span> to be removed.';
console.log('original:', str1);
console.log('modified:', str1.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/g, "$1"));
Parsing DOM is complex enough to not write it by hand.
If you can run it in a browser, here is the solution:
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
const dom = document.createElement('div');
dom.innerHTML = addStr;
const notranslate = dom.getElementsByClassName('notranslate');
for (let elem of notranslate) {
elem.remove();
}
console.log(dom.innerHTML);
To remove a specific HTML tag but to keep the innerHtml,
try this:
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
const dom = document.createElement('div');
dom.innerHTML = addStr;
const span = dom.getElementsByClassName('notranslate');
while(span.length) {
var parent = span[0].parentNode;
while(span[0].firstChild) {
parent.insertBefore( span[ 0 ].firstChild, span[0]);
}
parent.removeChild(span[0]);
}
console.log(dom.innerHTML); //Adding string: Idea No.<p>d</p> value Details
the method replace all tag because you use in RegExp the option 'gi' where 'gi' perform a global case-insensitive replacement. If you what replace a specific class you must define in regExp
I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>
I am using jQuery and Regex to search a text string for http or https and convert the string to a URL. I need the code to skip the string if it starts with a quote.
below is my code:
// Get the content
var str = jQuery(this).html();
// Set the regex string
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery(this).html(replaced_text);
Here is an example of my issue:
Text The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
The current code successfully finds the text that starts with http or https and converts it to a URL but it also converts the twitter URL. I need to ignore the text if it starts with a quote or is within an a tag, etc...
Any help is much appreciated
What about adding [^"'] to the exp variable?
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
Snippet:
// Get the content
var str = jQuery("#text2replace").html();
// Set the regex string
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery("#text2replace").html(replaced_text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text2replace">
The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
</div>
If you really just want to ignore the quotation marks, this could help:
var replaced_text = $("#selector").html().replace(/([^"])(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig, '$1$2');
This works for me:
This will recognize urls and convert them to hyperlinks, but will ignore urls, wrapped in " (quotes).
See the code below or this jsfiddle for a working example.
Example HTML:
<ul class="js-replaceUrls">
<li>
www.link-only-www.com
</li>
<li>
http://link-starts-with-HTTP.com
</li>
<li>
https://www.link-starts-with-https-and-www.com
</li>
<a href="https://link-starts-with-https.com">
Link in anchor tag
</a>
</ul>
RegEX:
/(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi
jQuery:
// RECOGNIZE URLS AND CONVERT THEM TO HYPERLINKS
// Ignore if hyperlink is found in HTML attr, like "href"
$('.js-replaceUrls').each(function(){
// GET THE CONTENT
var str = $(this).html();
// SET THE REGEX STRING
var regex = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi;
// REPLACE PLAIN TEXT LINKS BY HYPERLINKS
var replaced_text = str.replace(regex, "<a href='$1' class='js-link'>$1</a>");
// ECHO LINK
$(this).html(replaced_text);
});
// DEFINE URLS WITHOUT "http" OR "https"
var linkHasNoHttp = $(".js-link:not([href*=http],[href*=https])");
// ADD "http://" TO "href"
$(linkHasNoHttp).each(function() {
var linkHref = $(this).attr("href");
$(this).attr("href" , "http://" + linkHref);
});
See this jsfiddle for a working example.
I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();
I am trying to replace the contents of the alt="" attribute in the tag.
The replacment text comes from textarea input that is assigned to var alttext
The var oldtext contains tags with placeholders for replacing, like:
<img alt="placeholder" scr="pic.jpg" />
The placeholder needs to be replaced the contents of var alttext.
So far I have tried:
function replacer() {
var alttext = document.myform.alttext.value;
var oldtext = document.myform.oldtext.value;
var replacedtext = oldtext.replace("placeholder", 'alttext' )
document.myform.outputtext.value = replacedtext;
}
But it does not work.
How can the alttext variable contents be used to replace the placeholder?
Thank you very much to everyone!
function replacer() {
var alttext = document.myform.alttext.value;
var oldtext = document.myform.oldtext.value;
var replacedtext = oldtext.replace("placeholder", alttext);
document.myform.outputtext.value = replacedtext;
}
you were trying to replace with quotes around your variable (alttext) making it a string literal