0

I've seen several results for removing characters after a specific character - my question is how would I do that with a string?

Basically, this applies to any given string of data, but let's take a URL: stackoverflow.com/question

With given string, and in JS, I'd like to remove everything after ".com", assign ".com" to a variable, and assign the text before ".com" to a separate variable.

So, end result: var x = "stackoverlow" var y = ".com"


What I've done so far: 1) Using a combination of split, substring, etc. I can get it to remove pieces, but not without removing part of the ".com" string. I'm pretty sure I can do what I want to do with substring and split, I think I'm just implementing it incorrectly. 2) I'm using indexOf to find the string ".com" within the full string

Any tips? I haven't posted my actual code because it's become so garbled with all the different things I've tried (I can go ahead and do so if necessary).

Thanks!

6
  • What if the input is something like sub.domain.com/something - do you want the result to be sub.domain and .com? What if the input includes .net rather .com? Commented Mar 23, 2013 at 3:48
  • Ever heard of RegExp? Commented Mar 23, 2013 at 4:09
  • @nnnnnn The .com was there as a hypothetical - the whole script I'm creating would account for more than just the one suffix. Commented Mar 23, 2013 at 4:10
  • @Lenty, then why do you accept an answer that relies on .com? Commented Mar 23, 2013 at 4:12
  • Because its structure is the closest to what I was looking for :) Commented Mar 23, 2013 at 4:47

3 Answers 3

1

You should really look into Regular Expressions.

Here is some code that can get what you are trying to do:

var s = 'stackoverflow.com/question';

var re = /(.+)(\.com)(.+)/;

var result = s.match(re); 

if (result && result.length >= 3) {

    var x = result[1], //"stackoverlow"
        y = result[2]; //".com"

    console.log('x: ' + x);
    console.log('y: ' + y);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use regular expressions.

"stackoverflow.com".match(/(.+)(\.com)/)

results in

["stackoverflow.com", "stackoverflow", ".com"]

(Why would you want to assign .com to a variable, though?

1 Comment

Thank you! The .com was more of a hypothetical, used in my question.
0

"stackoverflow.com".split(/\b(?=\.)/) => ["stackoverflow", ".com"]

Or,

"stackoverflow.com/question".split(/\b(?=\.)|(?=\/)/)
=> ["stackoverflow", ".com", "/question"]

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.