0

I have tried for match last character

Here i am passing the One character like A or B, it returns the string ends with passing Character

var name = $(this).find('.name').text();
return name.match( /A$/i );
Liam
  • 27,717
  • 28
  • 128
  • 190
suresh
  • 47
  • 8
  • In your regex pattern, `$` stands to the end of the string, the anchor you are looking for is `^` which stands to the start of the string: `val = /^A/i.test(val) ? val : '';`. – Washington Guedes Jun 21 '17 at 10:24

4 Answers4

0

I am not 100% sure I understand the question correctly buy I suppose you are trying to achieve the following:

'monkey cow lion'.match(/^m.*$/)
Array[ "monkey cow lion" ]

Which will give you the entire string in case it matches.

If you are just looking for the word, I think you can go with:

'monkey cow lion'.match(/^m\w+/)
Array [ "monkey" ]
Liam
  • 27,717
  • 28
  • 128
  • 190
Westermann
  • 16
  • 4
0

Do you want to test if the string starts with a particular letter

You can do following:

name.charAt(0) === 'A' ? name : null; 
Prabodh M
  • 2,132
  • 2
  • 17
  • 23
0

You also can use the /g instead of /i.

I guess is is what you're looking for : http://regexr.com/3g74s

So in your JS it will look like this : text.match(/\b[Aa]\w*\b/g); where [Aa] is the letters you're looking for.

Or before test match you can lowercase or uppercase the string to test.

If you want to force the string length to be longer than 1 char, you can add {1,} as the following example : http://regexr.com/3g74v .

Maxime Lafarie
  • 2,172
  • 1
  • 22
  • 41
0

The simpliest way is to use Javascript native (ECMAScript 6) startsWith() function. It accepts two parameters:

string.startsWith(searchvalue, start)
  1. First is the string you want to search.
  2. Second one is optional and represents at which position to start the search.

so this must work (.toupperCase used to make it case insensitive):

return (name.toUpperCase().startsWith("A".toUpperCase())) ? name : null;

if you need to be case sensitive remove them:

return (name.startsWith("A")) ? name : null;
Damià
  • 31
  • 5