2010-05-18 121 views

回答

4
return theString.replace(/\ba[a-z]*n\b/ig, '') 
+1

這將替換整個單詞,他只需要替換'a'和'n'之間的字母。 – 2010-05-18 16:04:43

+0

謝謝我想用'<'和''而不是'a'和'n'我不能這樣做 – sundowatch 2010-05-18 17:26:49

+0

@sun:你想剝離HTML標籤嗎? – kennytm 2010-05-18 18:40:10

2

在Javascript:

var substitute = "\""; 
var text = "action"; 
var text = text.replace(/\b(a)([a-z]+?)(n)\b/gim,"$1" + substitute + "$3"); 
// result = a"n ... if what you really want is a double quote here 
+0

,我怎麼能取代 'asdasd' 而不是 '' – sundowatch 2010-05-18 15:56:04

+1

@sundowatch:只需更改分配給「替代」的字符串即可。 – 2010-05-18 15:59:52

+1

@Robusto:由於非貪婪量詞和缺少單詞邊界,這種解決方案對於以'a'開頭,以'n'結尾且在其他地方具有另一個'n'或'a'的單詞有問題在詞的中間。 – 2010-05-18 16:02:53

1

我真的不知道你想做什麼,但我猜從「行動」,以「CTIO」要去哪裏?

var foo = 'action'; 
if (foo.substr(0,1)=='a' && foo.substr(-1,1)=='n') { 
    var bar = foo.substr(1,foo.length-2); 
    alert(bar); // ctio 
}
1

試試這個下面

str.replace(/\ba(\w+)n\b/igm,''); 

在註釋使用的問題日以下注釋

var sub = "hello"; 
str.replace(/(<)(\w+)(")/igm,"$1" + sub + "$3"); 
+0

你的代碼是正確的,但我想用'<'和''而不是'a'和'n',我該怎麼辦? – sundowatch 2010-05-18 17:18:17