2

I have a variable which contains "j_id0:j_id11:i:f:pb:d:MyFieldName.input" (without the quotes).

Now I would like to capture "MyFieldName".

I had this:

var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(":(.*).input");
console.log("old text: " + test);
console.log("new text: " + testRE[1]);

which outputs this:

old text: j_id0:j_id11:i:f:pb:d:MyFieldName.input
new text: j_id11:i:f:pb:d:MyFieldName

So what I need is telling him that I want everything between the last occurence ":" and ".input", because now he finds the first ':' and stops there.

Any ideas how I can realise this?

Thanks!

4 Answers 4

2

One option that remains (among, presumably, many others) is:

var str = "j_id0:j_id11:i:f:pb:d:MyFieldName.input",
    fieldName = str.substring(str.lastIndexOf(':') + 1, str.lastIndexOf('.'));

JS Fiddle demo.

References:

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

Comments

1

This regex will work:

.*:(.*)\.input

1 Comment

@dystroy no. By default, a quantified subpattern is "greedy", that is, it will match as many times as possible and therefore match the last occurence of ":". Proof: jsfiddle.net/m4e6d/2
1

You could try this without regular expressions:

var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var fieldName = test.split(':').pop().split('.')[0];

3 Comments

This isn't a criticism of your approach, but is there a reason to not use testParts.pop().split('.')[0]?
@DavidThomas Very nice... I always forget about the pop method!
I'm not sure. I find regexes difficult to read and debug, so I stay away from them when I can
0

The problem with your regex is that it matches the first :, and then captures everything (.*) up until .input. To avoid this, you can make sure that your capture between : and .input cannot include more :.

This regex should work for you:

/:(\w+)\.input/

Fiddle

var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(/:(\w+)\.input/)
console.log("old text: " + test);
console.log("new text: " + testRE[1]); //MyFieldName

Group 1 will contain your field name.

I think the above should work for you, but if you need more than \w characters, you could use this instead to allow for things like "...:My.Field.Name.input" and capture "My.Field.Name":

/:([^:]+)\.input/

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.