I've got a function to remove the dash and everything that comes after it from a title.
This is the JS
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace(/ -.*$/g,"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
However this isn't working, it's not removing the dash or the text after.
I've tried just removing the dash like this:
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace('-',"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
And this works so I assume it's something to do with the regex? any ideas?
As discussed in OP's comments, this may be due to the class being present multiple times. You should then use document.querySelectorAll along with NodeList#forEach :
(function() {
document.querySelectorAll('.dash-remove').forEach(item => {
item.innerHTML = item.innerHTML.replace(/ -.*$/g, '');
});
})();
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
<h2 class="dash-remove">Testing - that function</h2>
Related
I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?
<script type="text/javascript">
var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);
</script>
Thanks a lot!
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
This is an old question, but I stumbled across it and thought I'd share the method I used:
var body = '<div id="anid">some text</div> and some more text';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
sanitized will now contain: "some text and some more text"
Simple, no jQuery needed, and it shouldn't let you down even in more complex cases.
Warning
This can't safely deal with user content, because it's vulnerable to script injections. For example, running this:
var body = '<img src=fake onerror=alert("dangerous")> Hello';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
Leads to an alert being emitted.
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
This is a solution for HTML tag and   etc and you can remove and add conditions
to get the text without HTML and you can replace it by any.
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| ||»|«|>/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.
#license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var res = tmp.textContent || tmp.innerText || '';
res.replace('\u200B', ''); // zero width space
res = res.trim();
return res;
}
you can use a powerful library for management String which is undrescore.string.js
_('a link').stripTags()
=> 'a link'
_('a link<script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
my simple JavaScript library called FuncJS has a function called "strip_tags()" which does the task for you — without requiring you to enter any regular expressions.
For example, say that you want to remove tags from a sentence - with this function, you can do it simply like this:
strip_tags("This string <em>contains</em> <strong>a lot</strong> of tags!");
This will produce "This string contains a lot of tags!".
For a better understanding, please do read the documentation at
GitHub FuncJS.
Additionally, if you'd like, please provide some feedback through the form. It would be very helpful to me!
For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
The selected answer doesn't always ensure that HTML is stripped, as it's still possible to construct an invalid HTML string through it by crafting a string like the following.
"<<h1>h1>foo<<//</h1>h1/>"
This input will ensure that the stripping assembles a set of tags for you and will result in:
"<h1>foo</h1>"
additionally jquery's text function will strip text not surrounded by tags.
Here's a function that uses jQuery but should be more robust against both of these cases:
var stripHTML = function(s) {
var lastString;
do {
s = $('<div>').html(lastString = s).text();
} while(lastString !== s)
return s;
};
The way I do it is practically a one-liner.
The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.
Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.
I realize this question is old, I just thought my solution was unique and wanted to share. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);
If you want to do this with a library and are not using JQuery, the best JS library specifically for this purpose is striptags.
It is heavier than a regex (17.9kb), but if you need greater security than a regex can provide/don't care about the extra 17.6kb, then it's the best solution.
Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
<script>
var chars = 55;
if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>
... The output would be:
This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.
You can try this
var chars = 55;
if ($('#mytext').text().length > chars){
var text = $('#mytext').text(); // div text
var chars_text = text.substring(0, chars); // chars text
var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span
$('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
Note: if you just need to replace the next one dot after chars you can
use '.' instead of /\./g
this way : With JQUERY Substring
<p>
this is test string with jquery . test 1 2 3 4 45 5 . test test test
</p>
<b></b>
<script>
var a = $('p').text();
var _output = '';
var _allow_index = 40;
if (a.length > _allow_index)
{
var x = a.split('.');
for(var i=0; i<x.length; i++)
{ if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
}
else { _output = a; }
$('b').html(_output + '<br>'+a.substr(_output.length,a.length));
</script>
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages.
Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text().
However here is a way for the given case:
var container = $('#mytext');
var length = 55;
var insert = '<br/>';
var text = container.text().trim(); // text() or html()
var dotPosAfterLength = text.indexOf(".", length);
if (dotPosAfterLength != -1) {
container.html(
text.substring(0, dotPosAfterLength+1)
+insert
+text.substring(dotPosAfterLength+1)
);
}
You just need to add this property in CSS.
<div id="mytext">
This is just a example. I need to find a solution.
I will appreciate any help. Thank you.
</div>
<style>
div#mytext{
word-wrap: break-word;
}
</style>
I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here
There is a static HTML file:
<html>
<body>
ABC
XYZ
foo
bar
</body>
</html>
Our question: How can I put in buttons/links (?) to this single, static HTML file, so that the people that are visiting this page can highlight given predetermined strings after clicking on the button/link on the page? With javascript? But how?
UPDATE: Place "ABC" from the above HTML into <big><b> tags like:
<big><b>ABC</b></big>
There are several ways you could do this.
a. Using plain javascript, you can try this:
1- Have a variable with the strings you want highlighted.
highlight = ['ABC', 'XYZ', ... ];
2- Make the function that highlights the strings from the highlight variable
makeHL = function(strings) {
// Get the HTML you want to search and replace strings on
myHTML = document.getElementsByTagName('body')[0].innerHTML;
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
strings.forEach(function(str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
document.getElementsByTagName('body')[0].innerHTML = myHTML
}
3- When the user clicks your link or your button, just call makeHL(highlights)
jsFiddle Here
Make sure that you include a Ecmascript5 shim such as es5-shim for use of .forEach() in browsers that don't support it.
b. Using a library like jQuery, it's easier to work around browser incompatibilities:
1- Include jQuery before the rest of the code:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
2- Have a variable with your replacements:
highlight = ['ABC', 'XYZ', ... ];
3- Make the function that highlights the strings from the highlight variable and bind it to the click event:
$('.makeHL').on('click', function() {
// Get the HTML you want to search and replace strings on
myHTML = $('body').html();
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
$.each(highlight, function(i, str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
$('body').html(myHTML);
});
jsFiddle Here
Working example
HTML:
<p>
<button class="highlight-text">Highlight "ABC"</button>
</p>
ABC
XYZ
foo
bar
JS:
(function(){
function highlightText(textToHighlight) {
var searchExpression;
searchExpression = new RegExp('(' + textToHighlight + ')', 'g');
document.body.innerHTML = document.body.innerHTML.replace( searchExpression, '<b>$1</b>' );
}
document.querySelector('.highlight-text').addEventListener(
'click',
function(){ highlightText('ABC'); },
false
);
})();
http://jsfiddle.net/medda86/9g8XD/
html
ABC
XYZ
foo
bar
<button class="button">Button</button>
Jquery
var predefinedStrings = new Array('ABC','bar');
var arrLength = predefinedStrings.length;
$('.button').click(function(){
for (var i = 0;i < arrLength;i++){
$('body').html($('body').html().replace(predefinedStrings[i],'<b>'+predefinedStrings[i]+'</b>'));
}
});
I would suggest using Jquery javascript library
JQUERY
function highlight(word,content){
//gi makes the replace recursive and case insensitive
var regex = new RegExp( '(' +word+ ')', 'gi' );
return content.replace( regex, bold );
}
function unhighlight(word,content){
var regex = new RegExp( '(' +bold(word)+ ')', 'gi' );
return content.replace( regex, strip );
}
function bold(word){
return "<b>"+word+"</b>";
}
function strip(word){
return word.replace("<b>","").replace("</b>","");
}
highlighted = null;
$(document).ready(function (){
$("body").delegate(".highlight","click",function (e){
var word = $(this).text();
var container = $("body");
var content = container.html();
if(highlighted!=word){
//this is optional if you would like to unhighlight prev selections
content = unhighlight(highlighted,content);
content = highlight(word,content);
highlighted = word;
container.html(content);
}
});
});
HTML
<html>
<body>
ABC
XYZ
foo
bar
ABC
XYZ foo FOO Bar ABC
<button class="highlight">ABC</button>
<button class="highlight">FOO</button>
</body>
</html>
Heres a FIDDLE
I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle