Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5260

Javascript get last part of variable strings

I have strings like that;

a-variable-part[]
another-string[x]

without knowing the length of each string i want to separate the first part of the string from what there's inside []

in the examples above I want to get:

do you know how?

Upvotes: 1

Views: 152

Answers (4)

jfriend00
jfriend00

Reputation: 707198

You can use a regex to find the two pieces like this:

function getParts(str) {
    var matches = str.match(/(^.*?)\[(.*?)\]/);
    if (matches) {
        return({first: matches[1], second: matches[2]});
    }
    return(null);
}

Working demo: http://jsfiddle.net/jfriend00/Nn63v/

To explain the regex, it matches a first group of characters that goes from the start of the string up until the first [ char. Then, it matches a second group of characters that is between the [ and ].

Upvotes: 4

bukart
bukart

Reputation: 4906

Best way to do this with a regex

var result = input.match( /^([^\[]+)\[([^\]]+)\]$/ );

Upvotes: 0

dfsq
dfsq

Reputation: 193261

If you run this:

'another-string[x]'.slice(0, -1).split('[');

it will give you an array of two elements: ["another-string", "x"]

Upvotes: 2

MickMalone1983
MickMalone1983

Reputation: 1054

At a basic level this will work:

var myString = 'foo[bar]';

var bitInBrackets = myString.split('[')[1].split(']')[0];// will be string 'bar'

If you're going to be doing a lot of string manipulation it's probably worth learning a bit about regex, but if this is all you want to do, and you know the strings will follow this format, the above will work fine.

Hope this helps

Upvotes: 0

Related Questions