3

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.

4
  • Please show us what you have tried so far Commented Aug 7, 2017 at 9:36
  • Can you make a demo/snippet explaining your problem Commented Aug 7, 2017 at 9:37
  • You probably require regex irrespective of javascript or jquery. Commented Aug 7, 2017 at 9:37
  • str.replace(/\..*$/, '.') Commented Aug 7, 2017 at 9:39

8 Answers 8

8

You can easily do it with .split() like this:

var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];

here is fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

For more efficiency, use text.split('.', 1)[0]);
@DanielAlder how is that more efficient? is there a source on this?
@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
2
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

2

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

0
text.substr(0, text.indexOf('.'));

Comments

0

Hope this helps.

var q = 'https://stackoverflow.com/questions/';
q = q.substring(0, q.indexOf('.'));
alert(q);

Comments

0

Try this

var yourString = "Hello. World";

yourString.substr(0, yourString.indexOf('.'));

Will give you the following output

Hello

Comments

0

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>

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.