remove " " from script [duplicate] - javascript

I have written the following code. But it is removing only not <br>
var docDesc = docDescription.replace(/( )*/g,"");
var docDesc1 = docDescription.replace(/(<br>)*/g,"");

You can achieve removing <br> with CSS alone:
#some_element br {
display: none;
}
If that doesn't fit your needs, and you want to really delete each <br>, it depends, if docDescription is really a string (then one of the above solutions should work, notably Matt Blaine's) or a DOM node. In the latter case, you have to loop through the br elements:
//jquery method:
$('br').remove();
// plain JS:
var brs = common_parent_element.getElementsByTagName('br');
while (brs.length) {
brs[0].parentNode.removeChild(brs[0]);
}
Edit: Why Matt Baline's suggestion? Because he also handles the case, where the <br> appears in an XHTML context with closing slash. However, more complete would be this:
/<br[^>]*>/

Try:
var docDesc = docDescription.replace(/[&]nbsp[;]/gi," "); // removes all occurrences of
docDesc = docDesc.replace(/[<]br[^>]*[>]/gi,""); // removes all <br>

Try this
var text = docDescription.replace(/(?: |<br>)/g,'');

Try "\n"...see if it works.

What about:
var docDesc1 = docDescription.replace(/(<br ?\/?>)*/g,"");

This will depend on the input text but I've just checked that this works:
var result = 'foo <br> bar'.replace(/(<br>)*/g, '');
alert(result);

You can do it like this:
var cell = document.getElementsByTagName('br');
var length = cell.length;
for(var i = 0; i < length; i++) {
cell[0].parentNode.removeChild(cell[0]);
}
It works like a charm. No need for jQuery.

I using simple replace to remove and br tag.
JavaScript
var str = docDescription.replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '');
jQuery
Remove br with remove() or replaceWith()
$('br').remove();
or
$('br').replaceWith(function() {
return '';
});

Related

Javascript - How can I replace text in HTML with text in script

I am new to javascript. I was thinking getelementbyid but i don't know how to make it work
Like the title, here is what I mean
For example I have in HTML:
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
So what I want is to make script to replace those fw_93 fw_94 to what I want.
For example
Instead of displaying "fw_93" I want it to display "9.3". Same with fw_94 to 9.4
Replace fw_ with nothing, divide the number by 10:
Array.prototype.forEach.call(document.getElementsByTagName('p'), function(el) {
el.innerHTML = parseInt(el.innerHTML.replace(/[A-Za-z_]*/, '')) / 10;
});
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Okay so select the tags.
Loop over the collection
read the html
match the string
replace the html
var ps = document.querySelectorAll("p");
for (var i=0; i<ps.length; i++) {
var p = ps[i];
var txt = p.innerHTML; //.textContent
var updated = txt.replace(/.+(\d)(\d)/, "$1.$2");
p.innerHTML = updated;
}
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Using JQuery
Not sure why I did it with JQuery, guess I wasn't paying enough attention. No point in me re-writing as there are already good answers in JS. Though I will leave this in case it's of use to anyone that is using JQuery.
You can loop though each <p> element and covert the contents, something like this:
$("p").each(function() {
var text = $(this).html();
var text = text.substring(text.indexOf("_") + 1);
var text = text[0] + "." + text.substring(1);
$(this).html(text);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
You may need to add validation depending on how reliable your input is.
Note that the code makes the following assumptions:
There will always be a _ followed by at least 2 digits
The . will always go after the first digit
Your HTML:
<p id="p1">init_value</p>
Your JS:
document.getElementById("p1").innerHTML = "new_value";

Writing line breaks to a <span> element using JavaScript?

My goal is to take an array, and write each element onto a HTML page using a <span> element with .textContent using a for loop. Only problem is that instead of:
Error1
Error2
I get:
Error1<br/>Error2<br/>
HTML code:
<p><span id="EBox"></span></p>
JS code:
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
for (var i = 0; i < eArray.length; i++) {
EBox.textContent = EBox.textContent + eArray[i] + '<br/>';
}
The entire system works, but it just ends up as one jumbled sentence. What can I change to make it add the line breaks? I've tried '<br>', '<br />' and '\n' with similar results.
Use .innerHTML .insertAdjacentHTML instead of .textContent as .textContent does not parse the HTML <br> but simply outputs it as text.
Also if you're appending to the HTML each time, it's better to use .insertAdjacentHTML as it does not reparse the previous HTML, thus making it much faster and less error prone than .innerHTML.
var strArr = ['foo', 'bar'];
strArr.forEach(function(str) {
document.querySelector('div').insertAdjacentHTML('beforeend', str + '<br>');
});
<div></div>
Instead of .textContent use .innerHTML.
I would also recommend building up a string first before using .innerHTML so the DOM isn't rebuilt each time...
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
var html = "";
for (var i = 0; i < eArray.length; i++) {
html += eArray[i] + '<br/>';
}
EBox.innerHTML = html;
I found a better answer here:
https://developer.mozilla.org/pt-BR/docs/Web/CSS/word-break
You can use CSS to do this, see below:
span{word-break: break-word;}
or
span{word-break: break-all;}
BREAKE-WORD will put the next word in a new line and BREAKE-ALL will break the text justifying the content, when it gets bigger than the div or span container.
I hope I'd help :)

Insert <span> in <p> element

I got like;
<p>Variable Text</p>
And I want to it to be;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function.
Try this
var txt = "Hello bye";
var dataArr = txt.split(' ');
var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";
Here is a demo
It's possible (the following assumes the p has an ID, like you said), in it's simplest form you can just do:
var paragraph = document.getElementById("pId");
paragraph.innerHTML = "Hello <span>World</span>";
Or if you want to use jQuery:
$("#pId").html("Hello <span>World</span>");
Or (as you said in comments, you want to keep the existing content, but wrap the last word in a span, you can do:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
DEMO
I would like to share a jQuery solution, which is regardless of any words defined in your p element
$("p").html(function(){
var mystring= $(this).text().split(" ");
var lastword = mystring.pop();
return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword);
});
Demo
In the demo above, I am splitting the string first, than am using pop to get the last index in the array, and than am adding span element and returning the string using join
$("document").ready(function(){
$("p").append("<span>world</span>");
});
With JQuery append
$("#paragraphId").append('<span>Text in span</span>');
jQuery is easier, and personally I think it's better to use than only javascript:
jQuery:
$("#paragraphID").append("<span>World</span>");
HTML:
<p id="paragraphID">Hello</p>

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

Markdown to convert double asterisks to bold text in javascript

i'm trying to make my own markdown-able textarea like Stackoverflow has done. The goal is to allow people to type **blah blah** in a textarea and have the output in a div be <span style="font-weight:bold;">blah blah</span>.
I'm having trouble with the javascript to find and replace to the **asterisks with the HTML.
here's a jsfiddle which has gotten the party started: http://jsfiddle.net/trpeters1/2LAL4/14/
here's the JS on that just to show you where I'm at:
$(document.body).on('click', 'button', function() {
var val=$('textarea').val();
var bolded=val.replace(/\**[A-z][0-9]**/gi, '<span style="font-weight:bold;">"'+val+'" </span>');
$('div').html(bolded);
});
and the HTML...
<textarea></textarea>
<div></div><button type="button">Markdownify</button>
any thoughts would be greatly appreciated!
thanks,
tim
The other answers fail when a char is immediately before or after the asterisks.
This works like markdown should:
function bold(text){
var bold = /\*\*(.*?)\*\*/gm;
var html = text.replace(bold, '<strong>$1</strong>');
return html;
}
var result = bold('normal**bold**normal **b** n.');
document.getElementById("output").innerHTML = result;
div { color: #aaa; }
strong { color: #000; }
<div id="output"></div>
None of the provided answers works in all cases. For example, the other solutions wont work if we have a space next to the double star, ie:
This will ** not ** be bold
So I wrote this:
function markuptext(text,identifier,htmltag)
{
var array = text.split(identifier);
var previous = "";
var previous_i;
for (i = 0; i < array.length; i++) {
if (i % 2)
{
//odd number
}
else if (i!=0)
{
previous_i = eval(i-1);
array[previous_i] = "<"+htmltag+">"+previous+"</"+htmltag+">";
}
previous = array[i];
}
var newtext = "";
for (i = 0; i < array.length; i++) {
newtext += array[i];
}
return newtext;
}
Just call it like this:
thetext = markuptext(thetext,"**","strong");
and it will work in all cases. Of course, you can also use it with other identifiers/html-tags as you like
(the stackoverflow preview should have this too).
Choose the perfect regex that will fit your needs.
If you don't want styling to span through new line and also using ([^*<\n]+) makes sure at least one character is in between styles or else ** without a character in-between will result will become invisible.
function format_text(text){
return text.replace(/(?:\*)([^*<\n]+)(?:\*)/g, "<strong>$1</strong>")
.replace(/(?:_)([^_<\n]+)(?:_)/g, "<i>$1</i>")
.replace(/(?:~)([^~<\n]+)(?:~)/g, "<s>$1</s>")
.replace(/(?:```)([^```<\n]+)(?:```)/g, "<tt>$1</tt>")
}
β€’The downside to the above code is that, you can't nest styles i.e *_Bold and italic_*
To allow nested styles use this πŸ‘‡
format_text(text){
return text.replace(/(?:\*)(?:(?!\s))((?:(?!\*|\n).)+)(?:\*)/g,'<b>$1</b>')
.replace(/(?:_)(?:(?!\s))((?:(?!\n|_).)+)(?:_)/g,'<i>$1</i>')
.replace(/(?:~)(?:(?!\s))((?:(?!\n|~).)+)(?:~)/g,'<s>$1</s>')
.replace(/(?:--)(?:(?!\s))((?:(?!\n|--).)+)(?:--)/g,'<u>$1</u>')
.replace(/(?:```)(?:(?!\s))((?:(?!\n|```).)+)(?:```)/g,'<tt>$1</tt>');
// extra:
// --For underlined text--
// ```Monospace font```
}
πŸ‘† If you want your style to span through new line, then remove \n from the regex. Also if your new line is html break tag, you can replace \n with <br>
Thank me later!
Why create from scratch? With so many open source editors out there, you should pick a code base you like & go from there.
http://oscargodson.github.com/EpicEditor/
http://markitup.jaysalvat.com/home/
custom component in react who receives bold like boolean
{(() => {
const splitText = theText.split('**');
return (
<TextByScale>
{splitText.map((text, i) => (
<TextByScale bold={!!(i % 2)}>{text}</TextByScale>
))}
</TextByScale>
);
})()}
If you are using jQuery, replace this:
$(document.body).on('click', 'button', function() {
with this:
$("button").click(function () {
The following regular expression will find your asterisk-wrapped text:
/\x2a\x2a[A-z0-9]+\x2a\x2a/
I updated your fiddle as an example: http://jsfiddle.net/2LAL4/30/
Your regex is broken, for one thing. You probably want something more like:
/\*\*[A-z0-9]+\*\*/gi
The * is a special character in regular expressions. If you want to match against a literal *, then you need to escape it with \.
For instance: http://jsfiddle.net/2LAL4/22/
However, even with this change there's still a fair ways to go before you get to where you really want to be. For instance, your example will not work if the text area contains a mix of bold and non-bold text.

Categories