-1

I need to get the jsmith part out of the following elements alt attribute

<img src="http://www.test.com" class="img-thumbnail" alt="John Smith (jsmith)">

So I'm running this

$('.img-thumbnail').attr('alt');

which gives me

"John Smith (jsmith)"

I need to get the 'jsmith' part out

any ideas?

Mohammad
  • 19,228
  • 14
  • 49
  • 73
  • 1
    Will the string you need to remove always be in (parenthesis) ? – Sinan Guclu Jul 07 '16 at 09:40
  • 1
    Once you have the attribute value you just need standard Javascript string functions to extract the required piece. What have you tried? Regex match? Or `.indexOf()` plus `.slice()`? Or you could use `.split()`. – nnnnnn Jul 07 '16 at 09:42
  • Yes, if the string is always be in (parenthesis) you can try Regex – Sree KS Jul 07 '16 at 09:45

4 Answers4

5

Try this

$('.img-thumbnail').attr('alt').match(/\(([^)]+)\)/)[1]

Please note that this will only work if you want to get the text inside brackets. FIDDLE. Hope this helps

Utkarsh Dixit
  • 3,476
  • 2
  • 12
  • 34
  • This gets want I need however it also gets the quotes. Thank you for you help. This guys @Aakash answer got exactly what I needed –  Jul 07 '16 at 09:48
  • Which way is better, the way your doing it or the way @Aakash is doing it. –  Jul 07 '16 at 09:53
  • @edward The both codes does the same thing..... But this code is little bit short.... – Utkarsh Dixit Jul 07 '16 at 09:54
  • Awesome, can you please tell me how the regex works? –  Jul 07 '16 at 09:55
  • It is explained perfectly in this question .... http://stackoverflow.com/questions/4736/learning-regular-expressions – Utkarsh Dixit Jul 07 '16 at 09:56
2

Use the following code:

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("John Smith (jsmith)");
console.log(matches[1]);
// Output jsmith
Aakash
  • 1,315
  • 12
  • 16
  • Thanks for your answer, this gave me exactly what I needed. can you please give me a short description of what its doing? –  Jul 07 '16 at 09:52
  • Sure, so we are using regular expression to get the value in the parenthesis. Here is the break down: `\(` - Match opening parenthesis, `(` - Begin to capture the string, `[^)]+` - Match one or more characters that are not `)` , `)` - End capturing the string, `\)` - Match the closing parenthesis. – Aakash Jul 07 '16 at 09:58
1

try this also,

var temp = $('.img-thumbnail').attr('alt');
temp.substring(temp.indexOf('(')+1,temp.indexOf(')'));
0
var value = $('img').attr('alt');
var newString = value.replace(new RegExp("\\(", "g") ,"~~~");
newString = newString.replace(new RegExp("\\)", "g") ,"~~~");
var finalString = newString.split('~~~');
alert(finalString[1])
prudvi raju
  • 485
  • 5
  • 17
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Brian Tompsett - 汤莱恩 Jul 07 '16 at 10:55