Keeping the excess whitespace in JavaScript - javascript

Hi i am trying to convert white space into
I have a tag in my html code <pre></pre> and contain blank space inside. I am originally trying to select the javascript value but maintaining the blank position. However i am awared that innerHTML does remove excess white space. Is there a way for me to keep the blank position. I am also trying to grab it before i do the innerHTML to do something of this sort
<script>
$(document).ready(function() {
var value = $("pre").val();
value = value.replace(" ", "&nbsp");
$("pre").val(value);
});
</script>
but it doesn't select the white space i guess.
Thank you for any help. I also don't have access to generate the html before it even gets display.

val method only works for form elements, for other elements you should html/text method instead.
$("pre").html(function(_, innerHTML) {
return innerHTML.replace(/\s/g, " ");
});

Related

Textarea.value doesn't manipulate the HTML

Setting the value of the textarea, won't be reflected in the HTML.
For instance,
If you have <textarea></textarea> in your HTML, and set its value to 'Hello' the HTML will remain unchanged and not <textarea>Hello</textarea>
I think this is what you want, use this to your w3schools example
<script>
function myFunction() {
var x = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
myTextarea.onkeyup=()=>myTextarea.innerText=myTextarea.value;
</script>
You seem to be working off some misconceptions. I take it you're expecting that line breaks in the text area will be reflected as line breaks in a paragraph if you insert it as the HTML of the paragraph. In HTML, all whitespace is collapsed into spaces, and line breaks in HTML source do not normally translate to breaks in HTML text flows. If you do want newlines to work in HTML, use a <pre></pre> element instead. Otherwise you'll need to convert newlines to <br> elements.
There's also the white-space CSS style that can change the way that whitespace is rendered.

Avoiding extra use of span

My question is that I have an html code <p> Hello World </p>
And want to change the css of every letter using JavaScript. Essentially, I will change the background color to make an animation. Is there a way to do this without making a span or some sort of tag around every letter and going through all that struggle?
I have my string array with colors and a method to call the correct color (data-index attribute).
Thanks!
EDIT: I have the entire word changing color and thought of an idea by making a function that iterates over the indexes of the innerHTML string and assigns a data-index to the letter's span by editing the function provided below by Cymen. Is this a good approach?
No, you will need to use a tag that supports background-color. You can easily wrap a string of characters in spans like so:
function wrapInSpans(string) {
return '<span>' + string.split('').join('</span><span>') + '</span>';
}
You would have to use a JavaScript function to wrap each character in a <span>.
window.onload = function() { // when everything loads, run the function
var elem = document.getElementById( "someId" );
var text = elem.innerHTML; // get the <p>'s text content
elem.innerHTML = ""; // then make the <p> empty
for( var i=0; i<text.length; i++ ) { // for each character in the text
elem.innerHTML += "<span>"+text[i]+"</span>";
}
};
Remember to change "someId" to the id of your <p> element.
You can access each individual character inside the for loop with text[i].
This would take quite a bit of code to spell out completely, but, if it's very important in your case to not actually add some type of wrapping element, then I believe this would be possible via a dynamically generated background image.
Roughly the steps would be:
Create a Range with a start and end around each character in the .textContents of the element you care about.
.getBoundingClientRect() on each range to get its rendered dimensions.
Draw rectangles of the desired color to a <canvas>.
Export the <canvas> as a data URI.
Use the data URI as a background-image.
Repeat for each block displayed element that you care about.
Be advised that there will, no doubt, be various edge cases in this approach and possible browser support limitations. Obviously just wrapping each character is a much simpler.

How can I Strip all regular html tags except <a></a>, <img>(attributes inside) and <br> with javascript?

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);

turn <br> into line breaks using javascript (not php)

I need to extract the text from a div with paragraphs and spans and other things and put it into a textarea. I need to load just the text, not the HTML.
For that, I can use:
loadtext = $('#mydiv').text();
However, I DO need to retain the line breaks.
For that, I'm doing:
loadtext = $('#mydiv').text().replace(/<br>/gm, '\r\n');
But it doesn't seem to be working, because when I load that text into a textarea, it's all flat with no line breaks. Am I doing something wrong?
$('#mydiv').text() has already been stripped of all HTML, including<br> elements, so this will not work. You need to modify the HTML of the #mydiv element and replace all <br/> elements, then retrieve the text.
$('#mydiv').find('br').each(function(){
$(this).after("\n")
.remove();
});
var loadtext = $("#mydiv").text();
An alternate solution is to use an intermediate element that's never added to the document.
var html = $('#mydiv').html(); // e.g. '<p>line 1</p><br><br><p>line 2</p>'
var text = $('<div>').html(html.replace(/<br\/?>/g, '\n')).text();
/* text =
"line 1
line 2"
*/
$('#mytextarea').text(text);
This supports <br> (HTML) and <br/>(XHTML).

regex to replace a string from the inner html of a div

i have a div that contains some html and text (html is added dynamically)the structure would be like
<div id="contentContainer">
<span>ProductA</span> ; <span>ProductB</span>; prod
</div>
i want to remove the last incomplete text (prod) from the inner html of the div contentContainer on submit button click
for this i was using regex returnText.replace(/\w+$/, ''); and it works fine
as i can not trim the text to last index of ';'
but not the issue is when user puts some special charaters in the incomplete text as pr\od
the regex fails
so is there any solution to trim the last appended text the inner html of the div
or can i trim the text to the last html tag and place ; after that
please suggest any solution
if you are using jquery you can pull out all span elements and replace innerHTML with them.
$("#contentContainer").html( $("#contentContainer span") );
That should clean rest things. Maybe not the best but i think its better then regexp on content.
Solution looks at the last DOM node in DIV, if it is a text node it changes text to semi-colon
var lastNode = $('#contentContainer').contents().last()[0]
if (lastNode.nodeType == 3) {
lastNode.textContent=';'
}
demo: http://jsfiddle.net/EhcLh/

Categories