2

What would be the quickest way to remove "everything" from a string, starting from the first "dot".

For example:

This.Is.A.Test

=> would become

This
2
  • 1
    For future benchmarking purposes, may I refer you to JS Perf? Commented May 20, 2012 at 20:32
  • Regex is unnecessary for something as simple as this. Commented May 20, 2012 at 20:32

5 Answers 5

4

You can use the the split() function like this:

"This.Is.A.Test".split(".")[0]; // will work even if there are no dots

Or you could use the substr() function in combination with the indexOf() function, like this:

var myStr = "This.Is.A.Test";
var justTheFirstBit = myStr.substr(0, myStr.indexOf(".")); // needs 1 dot minimum
Sign up to request clarification or add additional context in comments.

15 Comments

Fixed your substring function for you.
@mc10: substr is just as valid as substring. I'll be changing it back, although I appreciate the edit. :)
@ElliotBonneville - Too long, "This.Is.A.Test".replace(/\..+$/,""); is better.
@GGG: MDN says nothing about substr() being frowned upon.
second suggestion will not work if string contains no dots (indexOf returns -1). See my answer.
|
2

Alternatively,

var string = "This.Is.A.Test";
var newstring = string.substring(0, string.indexOf("."));

1 Comment

@PenchoIlchev I'm assuming the OP's input text has a dot in it, based on his/her question. If necessary, you could always check if the dot existed or not.
0

This should have complexity of O(2n) and should ever search up to the first dot (twice).

​var a = "This.Is.String";
var ind = a.indexOf(".");
ind = ind == -1 ? a.length : ind;
​var b = a.substring(0, ind);
​

Comments

0
$('#el').text( $('#el').text().split('.')[0] );

DEMO

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

Comments

0

             MDN - replace()


You can use the the replace() function like this:

"This.Is.A.Test".replace(/\..+$/,"");

This is the regular expression you need:

/\..+$/

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.