user648198
user648198

Reputation: 2020

How to get particular string content in Jquery

I have many select fields with IDs like:

"custom_view_custom_conditions_attribute_123_field_id"
"custom_view_custom_conditions_attribute_321_field_id"
"custom_view_custom_conditions_attribute_142_field_id"

I can get the id by using this code:

id = $(selector).attr("id").replace(/[^0-9]/g, "")

But I wanted to get this result "custom_view_custom_conditions_attribute"

How can I achieve this in jQuery?

Upvotes: 0

Views: 116

Answers (3)

Praveen
Praveen

Reputation: 56501

Try this regex

/_\d+_\w*/g

1) Begin with _
2) followed by numeric (+ denotes one or many)
2) again _
4) \w followed by alphanumeric (* denotes zero or many)

Upvotes: 0

Use RegExp

_\d.+

like this

var id = $(selector).attr("id").replace(/_\d.+/g, '');

fiddle Demo

Upvotes: 3

Michael Johnston
Michael Johnston

Reputation: 2382

You could do

id = $(selector).attr("id").replace(/_[0-9]{3}.*/g, "")

It removes any instance of _ + 3 numbers + rest of string.

By the way, .replace is pure Javascript, you don't need JQuery

Upvotes: 2

Related Questions