Using Variables in Replace() Method - Javascript - javascript

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

Related

Replacing texts with emoticons in JavaScript from Json values

I am trying to replace text with images.For example, abc:) should be converted into abc(and the respective emoticon).And I am using contenteditable element for doing the same.But, nothing seems to work.I tried using the replace() and html() functions but they don't work.
The link to my Codepen is: Link
And I don't want to use regex as I have to do more additions in my json file.Thanks!
HTML Code:
<div contenteditable="true" id='text-box'>
</div>
JS Code:
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
var img=new Image();
img.src=data.image;
img.setAttribute("class","image");
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
}
//$("#text-box").html(text.replace(data.value,img));
}
}
function getWord(text){
var word=text.split(" ").pop();
return word;
}
JSON data:
var data={
"value":":)",
"image":"persons-0016_large.png"
};
After the execution of my code,I get the output as abc[object HTMLImageElement] instead of the image itself.
Instead of creating an image object, replace the text by image tag like this.
var data={
"value":":)",
"image":"persons-0016_large.png"
};
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]');
var text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
//var img=new Image();
//img.src=data.image;
//img.setAttribute("class","image");
var img = "<img src='" + img.src +"' class='image' /> ";
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
} );
//$("#text-box").html(text.replace(data.value,img));
}
};
};
function getWord(text){
var word=text.split(" ").pop();
return word;
}

javascript textarea createTextNode()

I want to escape a string taken from a textarea using the createTextNode() method. Appending the TextNode to the textarea doesn't work.
function myFunc(){
var str = document.getElementById("tarea").value;
var chld = document.createTextNode(str);
var prnt = document.getElementById("tarea");
prnt.appendChild(chld);
}
If you want to have the browser do the escaping work for you, I'd probably use a temporary element for that, then use its innerHTML as the argument to createTextNode:
function myFunc(){
var prnt = document.getElementById("tarea");
var str = prnt.value;
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
prnt.appendChild(document.createTextNode(div.innerHTML));
}
myFunc();
<textarea id="tarea">Testing & < ></textarea>
But minimally escaping HTML is very simple, you don't necessarily need to go whole-hog:
str = str.replace(/&/g, "&").replace(/</g, "<");
(No need for >, it's fine as it is if you're not inside a tag.)
E.g.:
function myFunc(){
var prnt = document.getElementById("tarea");
var str = prnt.value;
str = str.replace(/&/g, "&").replace(/</g, "<");
prnt.appendChild(document.createTextNode(str));
}
myFunc();
<textarea id="tarea">Testing & < ></textarea>
Note that both of those append, because that's what your code was trying to do; they don't replace the content of the textarea. If you want to do that, set its value to "" before appending the text node.

replace all img tags with alt in div innertHTML

I have this code:
var str = document.getElementById('mesajyazi').innerHTML;
alert('input: '+str);
// first create an element and add the string as its HTML
var container = $('<div>').html(str);
// then use .replaceWith(function()) to modify the HTML structure
container.find('img').replaceWith(function() { return this.alt; })
// finally get the HTML back as string
var strAlt = container.html();
alert('output: '+strAlt);
It doesn't work.
But if I change var str to simple string text.
var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image';
It works.
P.S. - inspired by this Replace all <img> tag with img alt text :)

regular expression replace with prototype?

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

Select a Tag with a Selector from a Text Variable using jQuery

I have a string which contains text and some <a> tags in it; I want to know how I can select a tag from the variable and loop it. I tried the following but it didn't work:
var text = `some string here with http:something.com more string and more links also`;
$('a', text).each(function() {
var string = $(this).html();
$(this).html(string.substring(0, length-1)+(string.length > length ? end : ''));
});
You need to wrap the text in a div (or other element) then find() it:
var text = 'some string here with http:something.com more string and more links also';
text = $('<div>' + text + '</div>');
text.find('a').each(function() {
var length = 10;
var end = '...';
var string = $(this).html();
$(this).html(string.substring(0, length) + (string.length > length ? end : ''));
});
var text = text.html();
// Put it into a textarea
$('#myTextarea').val(text);
Replace
$('a', text).each(function() {
with
$(text, 'a').each(function() {
and see if it works.

Categories