Jason Wells
Jason Wells

Reputation: 889

Getting a partial value from a string in jQuery

Let's say I have a input box with the value of "foo_bar"

I want to assign foo to a variable, as well as bar. I never know the lengths of each of those. Essentially, anything to the left of the _ should be one variable, and everything to the right should be another.

How would you do this in jQuery?

Upvotes: 2

Views: 488

Answers (4)

elclanrs
elclanrs

Reputation: 94101

For the sake of variety:

var
str = 'foo_bar',
left = /(.+)_/.exec(str)[1],
right = /_(.+)/.exec(str)[1]

Upvotes: 0

adeneo
adeneo

Reputation: 318182

var a = 'foo_bar'​;
​var b = a.split('_')​;

​var left = b[0]​;
var right = b[1​];

Upvotes: 1

Aidiakapi
Aidiakapi

Reputation: 6249

You could use this code:

var str = "foo_bar"; // Change with input data
var index = str.indexOf("_");
if (index < 0) return false; // Change this with your '_' not found code
var foo = str.substr(0, index);
var bar = str.substr(index + 1);

Upvotes: 1

carlosfigueira
carlosfigueira

Reputation: 87218

You don't need jQuery for that, you can do it in plain JavaScript. A regular expression is one alternative, or if you know that you'll always have the '_' separator, you can use the indexOf method to find its position and split from there.

Or with an example:

var val = $("#inputId").val();
int separatorIndex = val.indexOf('_');
var first = val.substring(0, separatorIndex);
var second = val.substring(separatorIndex + 1);

Upvotes: 1

Related Questions