2015-11-06 35 views
0

我有以下字符串查找子串位置轉換爲字符串使用Javascript

"www.mywebsite.com/alex/bob/a-111/..." 
"www.mywebsite.com/alex/bob/a-222/..." 
"www.mywebsite.com/alex/bob/a-333/...". 

我需要找到在他們每個人的A-xxx和使用它作爲一個不同的字符串。 有沒有辦法做到這一點? 我試過使用indexOf(),但它只適用於一個字符。任何其他想法?

+1

這聽起來像一個XY問題。你需要這樣做的原因是什麼? –

+0

你試過Google嗎? http://www.w3schools.com/jsref/jsref_substring.asp – navigator

+3

@navigator你讀過那篇文章嗎?它是關於檢索字符串的一部分,而OP想要在另一個字符串中找到一個字符串的索引。另外,w3fools等等...... –

回答

4

您可以使用正則表達式

var string = "www.mywebsite.com/alex/bob/a-111/..."; 
 

 
var result = string.match(/(a-\d+)/); 
 

 
console.log(result[0]);

或全部匹配值

var strings = "www.mywebsite.com/alex/bob/a-111/..." + 
 
    "www.mywebsite.com/alex/bob/a-222/..." + 
 
    "www.mywebsite.com/alex/bob/a-333/..."; 
 

 
var result = strings.match(/a-\d+/g) 
 

 
console.log(result.join(', '));

0
var reg=/a-\d{3}/; 
text.match(reg); 
+0

請考慮添加更多關於您的答案的信息/解釋。 https://stackoverflow.com/help/how-to-answer – potame

相關問題