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>
Related
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
Is there a way to replace/remove the text only after a certain character using jQuery or Javascript? I want to remove text after the dot '.' from an element.
You can easily do it with .split() like this:
var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];
here is fiddle
var string = "Test String.Test String 2".split('.')[0];
console.log(string)
Will give you the output:
Test String
Here is a working example:
https://jsfiddle.net/zr2wg90d/
Your question is a bit unclear. But to remove all text after the first '.'(dot) This can do the trick with an input field. There are a lot of ways to achieve this. This is a solution without jQuery.
function removeAfterDot() {
var test = document.getElementById("myInput").value;
alert("String before remove: " + test);
test = test.substr(0, test.indexOf('.'));
alert("String after remove: " + test);
}
<input type="text" id="myInput" onchange=removeAfterDot();>
text.substr(0, text.indexOf('.'));
Hope this helps.
var q = 'https://stackoverflow.com/questions/';
q = q.substring(0, q.indexOf('.'));
alert(q);
Try this
var yourString = "Hello. World";
yourString.substr(0, yourString.indexOf('.'));
Will give you the following output
Hello
you can use this. split any string at the character you give it.
<p>first part . second part</p>
remove
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('a').click(function(){
var the_string = $('p').text();
var removed = the_string.split('.', 1);
$('p').text(removed);
});
</script>
for me splice works, I basically use this for removing characters after a hyphen or a comma etc.
var text = 'Tellme.more';
text.split('.')[0]);
//Consoles out -> Tellme
I have a string in which there are continous occurances of a font tag
<font color="blue">DATA ENTRY</font>
and in some cases like this
<font class="beat">DATA ENTRY</font>
I want to replace the 2 tags with
So that it looks like this
<p>DATA ENTRY</p>
I tried this ,can anyone please suggest me help.Thanks.
text = text.replace('<font [^"]*>',<p>).replace('</font>','');
block.outerHTML = "<p>" + block.innerHTML + "</p>"
where block is any HTML block
it just left to select it correctly with:
var block = document.querySelector(".selector");
If you want to stick with your simple string manipulation, you need to use regular expressions and correct the replacements in your replace calls:
text = text.replace(/<font[^>]*>/g,'<p>').replace(/<\/font>/g,'</p>');
Since you just need to replace the string you can do this with just one replace statement.
text = text.replace(/<(\/*)font[^>]*>/g, '<$1p>');
If you using jQuery with replaceWith
$('font').replaceWith('<p>DATA ENTRY</p>');
First of all the font tag is deprecated and should not be used.
Get an array of the tags you want to replace.
var elems = document.getElementsByTagName('font');
Go through loop and replace old HTML with new HTML
for (var i = 0; i < elems.length; i++)
{
var target = elems[i].innerHTML;
elems[i].innerHTML = target.replace(/(<p)/igm, '<font').replace(/<\/p>/igm, '</font>');
}
Note: This is not tested but should work.
Try like this :
$('font').contents().unwrap().wrap('<p/>');
In javascript, you can do something like this :
var str="<font>hello world</font>";
str = str.replace(/<font>/, "<p>");
str = str.replace(/<\/font>/,"</p>");
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
I'd like to select all occurances of <br /> that are within a paragraph <p></p> with a regular expression in JS. Currently I just select all <br /> like this:
var regex = /<br\s*[\/]?>/gi;
But doing this gives me trouble at some point because of what I'm trying to do with the selection. I need a more precise regex since breaks in headlines etc. are irrelevant to me.
If you are wondering about the context of this, I want to replace the <br />'s with two paragraphs with suitable classes to act like a <br /> but to indent the text after the break like this:
function removeEmptyNodes(selector)
{
$(selector).each(function() {
if ($(this).html().replace(/\s| /g, '').length == 0)
$(this).remove();
});
};
function assignIndents()
{
var str = $("#content").html();
var regex = /<br\s*[\/]?>/gi;
$("#content").html(str.replace(regex, "</p><br /><p>"));
$('br').prev('p').addClass('br');
$('br').next('p').addClass('indent');
removeEmptyNodes('#content p');
$('br').next('.scroller').children('p').first().addClass('indent');
$('br').replaceWith('');
removeEmptyNodes('#content p');
};
Edit:
My goal is that I have a paragraph with one or several line breaks. Like this simple case: <p>with some text <br />and another line<p>. I want the text after the line breaks to be indented and to be in a p of their own. So I need to split my original p. I don't want to add in divs or anything else nested in the original paragraphs. I need a bunch of sibling p tags at the end like this: <p class="br">with some text</p><p class="indent">and another line<p>
By which way I replace the <br />'s to split the p's does not matter to me...
Why don't you just find all without a regex?
$('p').each(function(){
var brs = $('br', this); //all <br>s withing this <p>
//do something with brs
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/
UPDATE:
Here is what you want with your new spec:
$('p').each(function(){
var html = this.innerHTML;
var htmlArray = html.split('<br>');
var new_html = htmlArray[0];
for(var i = 1; i < htmlArray.length; i++){
new_html += "<div class='break'>"+htmlArray[i]+"</div>";
}
this.innerHTML = new_html;
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/8/
UPDATE with no nesting:
JS:
$('p').each(function(){
var html = this.innerHTML;
var htmlArray = html.split('<br>');
var new_html = "<p>"+htmlArray[0]+"</p>";
for(var i = 1; i < htmlArray.length; i++){
new_html += "<p class='break'>"+htmlArray[i]+"</p>";
}
$(this).replaceWith(new_html);
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/11/
Use a Jquery selector instead of regex: $('p br')
Update 2:
$('#content')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
})
.wrap("<p>");
var br = $('#content br');
br.prev('p').addClass('br');
br.next('p').addClass('indent');
br.remove();
http://jsfiddle.net/wWsht/