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.
8 Answers
You can easily do it with .split() like this:
var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];
here is fiddle
3 Comments
Daniel Alder
For more efficiency, use
text.split('.', 1)[0]);Dror Bar
@DanielAlder how is that more efficient? is there a source on this?
Daniel Alder
@DrorBar Not really, but Imagine the input string has 10000 dots. then, the split function will create 10000 array elements, but only the first one is used. with the second parameter, you add an exit condition to the loop of the split function
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/
Comments
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();>
Comments
you can use this. split any string at the character you give it.
<p>first part . second part</p>
<a href="#">remove</a>
<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>
str.replace(/\..*$/, '.')