whole word match in javascript

I am using javascript in my webpage. I am trying to search a single whole word through textbox. Say I search: 'me' , I should find all the 'me' in the text, but not find 'memmm' per say.

I am using javascript's search('my regex expression') to perform the current search (with no success).

Thank you!

Edit: After several proposals to use the \b switches [which don't seem to work] I am posting a revised explanation of my problem:

amm, from some reason this doesn't seemt to do the tricks. Assume the following javascript search text:

<script type='text/javascript'>
var lookup = '\n\n\n\n\n\n2    PC Games        \n\n\n\n';
lookup  = lookup.trim() ;
alert(lookup );
                var tttt = 'tttt';
                alert((/\b(lookup)\b/g).test(2));

</script>

Moving lines is essential

Answers:

Answer

To use a dynamic regular expression see my updated code:

new RegExp("\\b" + lookup + "\\b").test(textbox.value)

Your specific example is backwards:

alert((/\b(2)\b/g).test(lookup));

Regexpal

Regex Object

Answer

Use the word boundary assertion \b:

/\bme\b/
Answer

You may use the following code:

var stringTosearch ="test ,string, test"; //true
var stringTosearch ="test string test"; //true
var stringTosearch ="test stringtest"; //false
var stringTosearch ="teststring test"; //false

if (new RegExp("\\b"+"string"+"\\b").test(stringTosearch)) {
  console.log('string found');
  return true;
} else {
  return false;
}
Answer
<script type='text/javascript'>
var lookup = '\n\n\n\n\n\n2    PC Games        \n\n\n\n';
lookup  = lookup.trim() ;
alert(lookup );
                var tttt = 'tttt';
                alert((/\b(lookup)\b/g).test(2));

</script>

It's a bit hard to tell what you're trying to do here. What is the tttt variable supposed to do?

Which string are you trying to search in? Are you trying to look for 2 within the string lookup? Then you would want:

/\b2\b/.test(lookup)

The following, from your regular expression, constructs a regular expression that consists of a word boundary, followed by the string "lookup" (not the value contained in the variable lookup), followed by a word boundary. It then tries to match this regular expression against the string "2", obtained by converting the number 2 to a string:

(/\b(lookup)\b/g).test(2)

For instance, the following returns true:

(/\b(lookup)\b/g).test("something to lookup somewhere")

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.