2011-10-25 68 views
1

如何在javascript上搜索文本。在javascript上搜索文本

var v=20; 
str = "The rain 20 in SPAIN stays mainly in the plain"; 
var patt1=/ain v/gi; 
var n = str.match(patt1); 
alert(n); 

我正在尝试,但没有得到任何结果。 我在哪里错了,任何哥们可以请你帮我一把。

+1

什么'str'?它没有定义 – hvgotcodes

+0

你想要搜索什么? –

+0

对不起,我更新了我的问题,请再看一遍。 – mdivya

回答

1
var v = 20; // Variable part of search query 
var str = "The rain 20 in SPAIN stays mainly in the plain"; // String to search 
var n = str.match('ain ' + v); // The searching, returns null if not found or the matches found. Notice the 'ain' string has been added (this can of course be changed) 

if(n != null){ // if not null 
    alert(n + ' found!'); 
}else{ // if null 
    alert(v + ' not found...'); 
} 

我认为这将帮助你:http://jsfiddle.net/xFeAH/

+0

谢谢joey,它的工作很好... – mdivya

1
var v=20; 
var str = "The rain 20 in SPAIN stays mainly in the plain"; 
var patt1=new RegExp("ain " + v, "gi"); 
var n = str.match(patt1); 
alert(n); // alerts 'ain 20' 

Example

1

我可能会错过了点,因为问题是非常广阔的,但你也可以使用str.indexOf(findThisString)