0

I use a 'change'-function to put the value of selectbox into an input

$("#afa_select").change(function() {
    var nd_value = $('#afa_select :selected').text();
    $("#nd_hidden").val(nd_value);
});

The options of the selectbox contain the following strings:

text 10 Jahre
another text 6 Jahre
just another text 12 Jahre
another text with a figure e.g. 1000 6 Jahre
another text with a figure e.g. 3234 6 Jahre

I need to find the number in front of the string " Jahre" and put this value into the input #nd_hidden.

4
  • is the position of "Jahre" always the same? Commented Jan 7, 2014 at 15:43
  • 1
    This isn't a jQuery thing, it's a JavaScript thing. What have you tried? Where are you getting stuck? Commented Jan 7, 2014 at 15:43
  • Can you use that number as the attribute for the options, it would be easier to read that way, just a suggestion. Other way is to do it with regex. Commented Jan 7, 2014 at 15:43
  • If 'Jahre' always going to be there you can simply do - nd_value[nd_value.length-7], but I would still do it regex way Commented Jan 7, 2014 at 15:46

2 Answers 2

5

This is trivial with a regular expression:

var text = "another text with a figure e.g. 1000 6 Jahre";
var result = /(\d+) +Jahre/.exec(text);
if (result) {
    console.log(result[1]); // "6"
}

If you need it as a number:

var num = parseInt(result[1], 10);

The regular expression says: "Find the first match in the string that's a series of digits followed by one or more spaces followed by the characters Jahre and capture the digits in a capture group." result will be null if no match was found. If a match is found, the contents of the first capture group are in result[1].

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

Comments

2

you could also split the string on a space and get the n-2 position if you don't want to use regular expressions.

var selectNumber = nd_value.split(" "); 
var yourNumber = selectNumber[selectNumber.length-2]; 

console.log(yourNumber); 

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.