Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

regex - How can I match a whole word in JavaScript?

I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "memmm" per say.

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

After several proposals to use the switches (which don't seem to work) I am posting a revised explanation of my problem:

For some reason this doesn't seem to do the trick. Assume the following JavaScript search text:

var lookup = '





2    PC Games        



';
lookup  = lookup.trim() ;
alert(lookup );

var tttt = 'tttt';
alert((/(lookup)/g).test(2));

Moving lines is essential


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To use a dynamic regular expression see my updated code:

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

Your specific example is backwards:

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

Regexpal

Regex Object


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...