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
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.
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>");
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'm a newbie in using RegEX and I could really use some help.
I'm doing some string replacements and I currently get the output
<div /foo>
Instead of
</div>
str = "[foo][/foo]";
Regex used:
str= str.replace(/\[/g, '<div ').replace(/\]/g, '>');
Output wanted:
<div foo></div>
Can someone help me to replace the string in the right way?
Thank you very much!
Not much content to your question so I just posted something which gets the job done. Note this assumes you do not care about anything after the opening tag, it only keeps the name of the tag and replaces it by </tagname>.
var str = "<div /foo>";
var replaced = str.replace(/<(\w+).*/, '</$1>')
// "</div>"
This one could suit your needs:
\[([^\]]+)\](.*?)\[/\1\]
Replace with: <div $1>$2</div>
Visualization by Debuggex
Demo on RegExr
PS: don't forget to escape the / if using JavaScript's regex literal, i.e.:
/\[([^\]]+)\](.*?)\[\/\1\]/g
How about:
str= str.replace(/\[(.+?)\]\[\/\1\]/g, '<div $1></div>');
You can do like this also.
var str = "[foo][/foo]";
//replace <, > with [, ]
var signReplace = str.replace(/\[/g, '<').replace(/\]/g, '>');
tagReplace = signReplace.replace(/foo/g, 'div'); //replace div with foo
I want to format this date: <div id="date">23/05/2013</div>.
First I want to split the string at the first / and have the rest in the next line. Next, I’d like to surround the first part in a <span> tag, as follows:
<div id="date">
<span>23</span>
05/2013</div>
23
05/2013
What I did:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function() {
$("#date").text().substring(0, 2) + '<br />';
});
</script>
See the JSFiddle.
But this does not work. Can someone help me with jQuery?
Using split()
Snippet :
var data =$('#date').text();
var arr = data.split('/');
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
Fiddle
When you split this string ---> 23/05/2013 on /
var myString = "23/05/2013";
var arr = myString.split('/');
you'll get an array of size 3
arr[0] --> 23
arr[1] --> 05
arr[2] --> 2013
Instead of using substring with a fixed index, you'd better use replace :
$("#date").html(function(t){
return t.replace(/^([^\/]*\/)/, '<span>$1</span><br>')
});
One advantage is that it would still work if the first / is at a different position.
Another advantage of this construct is that it would be extensible to more than one elements, for example to all those implementing a class, just by changing the selector.
Demonstration (note that I had to select jQuery in the menu in the left part of jsfiddle's window)
You should use html():
SEE DEMO
$(document).ready(function(){
$("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));
});
try
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
<div id="date">23/05/2013</div>
var arr = $('#date').text().split('/');
console.log(arr);
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
use this
<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
var x = $("#date").text();
x.text(x.substring(0, 2) + '<br />'+x.substring(3));
});
</script>
Try this
$("div#date").text().trim().replace(/\W/g,'/');
DEMO
Look a regular expression
http://regexone.com/lesson/misc_meta_characters
enjoy us ;-)
var str = "How are you doing today?";
var res = str.split(" ");
Here the variable "res" is kind of array.
You can also take this explicity by declaring it as
var res[]= str.split(" ");
Now you can access the individual words of the array.
Suppose you want to access the third element of the array you can use it by indexing array elements.
var FirstElement= res[0];
Now the variable FirstElement contains the value 'How'