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

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/

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.

how to wrap all matches of given string with html tag and append it to a template of a directive

Let's suppose I have a string like this:
Some text 321-ABC some text some text some text 761-DAW some text 612-AOS some text some text 733-OQA
It is passed to the directive scope. Now I want to display whole text with matches for /\d\d\d-\X\X\X/ wrapped with
<span ng-click=someFunction(matchedString)>matchedString</span>
How can I do this? What's the best practice?
Let' say your text is stored in text, and your div containing the text is called container.
The code of your container should be
<div ng-model="container" ng-bind-html="parsedText"></div>
Now in your code
$scope.processText = function() {
$scope.parsedText = $scope.text.replace(/([0-9]{3}-[A-Z]{3})/g, '$1');
};
This piece of code will replace every one of your codes with a link that you can click.
(I'm more of an Angular than AngularJS guy, so replace the link with whatever allows you to do what you want)

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).

insert content to already inserted content

well, I'm stuck and hope that you can help.
I created a text-example and put it to the end of the post. Thank you in advance.
On a site there are e.g. 50 entries - like comments. Some p-elements in some of those entries are containing a special text. This is just a snippet how I get the special text.
$("p:contains('special text')")
I want to get the parent div-element, too and clone the special text and the div-text.
$("p:contains('special text')").parent("div").clone()
Also I want to insert the content a div-element with id=fortext:
$("#fortext").append($("p:contains('special text')").parent("div").clone())
Now, and that's the point where I'm stuck, there are some entries containing a list point. I get the listpoint this way:
$("li:contains('listpoint text'):last").clone()
I'm cloning the 'text' because the text would be removed from the entries.
The entry-list however starts with entry#1 and ends with entry#50.
It has a chronology. By cloning the p-elements content and inserting it in my div the chronology of the entries is adhered.
I wanted to add the listpoint(s) as well. If I use append like:
$("#fortext").append($("p:contains('special text')").parent("div").clone()).append($("li:contains('listpoint text'):last").clone());
The content of the li-element is inserted,yes, but after the inserted p-elements content.
How can I insert the li-elements content to the p-elements content? So that the chronological order of the entries is hold?
entry#1
special text 1
entry#2
no text
entry#3
listpoint text
entry#4
special text 2
//
My output is:
special text 1 div text
special text 2 div text
listpoint text
//
My output should be:
special text 1 div text
listpoint text
special text 2 div text
Edit
You can find the html-structure I'm referring to here
I don't totally grasp what you are trying to accomplish, but it seems to me it would be easier to just clone everything to maintain the order you want, and then prune out what you don't want.
Something like:
var $cloned = $(...).clone();
$cloned.find("p.some-selector").addClass("keep");
$cloned.find("ul.another-selector").addClass("keep");
$cloned.find("p,ul").not(".keep").remove();
$cloned.find("p,ul").removeClass("keep");
$("#fortext").append($cloned);

Categories