Andrew Defee
Andrew Defee

Reputation: 13

JS - Remove all characters before/after a string (and keep that string)?

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!

Upvotes: 0

Views: 4862

Answers (3)

Koterpillar
Koterpillar

Reputation: 8104

Use regular expressions.

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

results in

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

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

Upvotes: 1

Kashif
Kashif

Reputation: 1263

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);
}

Upvotes: 1

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

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

Or,

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

Upvotes: 0

Related Questions