JavaScript RegExr. Parsing html into text - javascript

I would like to convert a html code into text by using regexr.
I am a beginner and I don't really know how to do it with split() and replace()...
For example:
const = myArtcle {
article: <p class="some-style">Some text with 094blabla.</p>
<img src="#" /><p class="style"> etc...</p>.
}
I tried this:
const textArticle = myArticle.article;
const deleteHTML = new RegExp(/\<(.*?)\>/);
const parsingText = () => {
textArticle.split(deleteHTML, '');
return (textArticle);
}
And I would like to have a parahraph:
Some text with 094blabla. etc...
instead of the html tags with the paragraph (so I want to remove all the html tags and only get the paragraph)
I would like to do it with RegExr and function JavaScript only.

Related

convert textarea value to html content using p tags

need to convert a textarea value to html content with p tags instead of new lines
this is my way - it works - but maybe there is a more native way or a predefined function to do the same
$('button').on('click', function(){
let a = $('#tx').val();
let html = '<p>' + a.trim().replace('\n', '</p>\n<p>') + '</p>';
console.log(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id='tx'>
lorem
ipsum
</textarea>
<button>CLICK</button>
In JavaScript you can split by newline and get an array. You can map that with template interpolation to wrap tags around. Utilizing the regex /\n+/ will ignore multiple succeeding newlines.
const text = "Hello\nWorld!\n\nHello\nmy\nfriend";
const html = text.split(/\n+/).map(e => `<p>${e}</p>\n`);
And a console.log(html); looks like this:
(5) ["<p>Hello</p>↵", "<p>World!</p>↵", "<p>Hello</p>↵", "<p>my</p>↵", "<p>friend</p>↵"]

Converting some text within an element to an element itself using JavaScript

Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.

how to post HTML code without the browser rendering

I'm to build a forum for the project, but right now I'm facing this problem where I want users to be able to post their HTML source code as it works in this forum.
But the problem is that the code runs or scatters my design when retrieve from my DB.
I tried using repalce() in jQuery but I could only replace < with < but I want a function to be able to replace others such as >,",' and & so my question is how can I update this function.
function convert(div){
var str = $(div).html();
var str2 = str.replace(/</g,"<");
var sta = $(div).html(str2);
return sta;
}
The above code work to replace the < but when I try including >,",' and & in the function it will stop work how can i make it work.
Thanks in advance.
Stick it in <pre> or <code> tags, or both, and make sure you use text() when inserting the content to the tag
function convert(div){
var str = $(div).html();
var sta = $('<code />', {text : str});
return sta;
}
var result = convert( $('#test') );
$('#result').html(result)
#result {
white-space : pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<span>
<p>TEST</p>
</span>
</div>
<br />
<div id="result">
<code> will preserve the code, and <pre> will preserve whitespace, but there's also the CSS white-space property, that can act as a <pre> tag using the pre setting

Remove every html tag with JsHtmlSanitizer

I finnally got the JsHtmlSanitizer working as a standalone clientside script.
Now I'd like to remove all HTML-Tags from a string and not just script-tags and links.
This example
html_sanitize('<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"><\/script>');
returns "hello" but I'd like to remove all tags.
Why not use regular expressions to remove all HTML tags after sanitizing?
var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
var output = null;
output = html_sanitize(input);
output = output.replace(/<[^>]+>/g, '');
This should strip your input string of all html tags after sanitization.
If you want to do just basic sanitization (removing script and style tags with their content and all html tags only) you could implement the entire thing within regex. I have demonstrated an example below.
var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
input += '<script> if (1 < 2) { alert("This script should be removed!"); } </script><style type="text/css">.cssSelectorShouldBeRemoved > .includingThis { background-color: #FF0000; } </style>';
var output = null;
output = input.replace(/(?:<(?:script|style)[^>]*>[\s\S]+?<\/(?:script|style)[^>]*>)|<[^>]+>/ig, '');
Use this javascript function below to remove all html tags from the string you get from html_sanitize().
var output = html_sanitize('<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"><\/script>');
output = output.replace(/(<.*?>)/ig,"");
Hope it helps :)

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources