2017-06-28 14 views
0

数字とテキストの文字列があります。文字列には常に "9"で始まり、8文字の長さの数字が必要です。私はどうすればいいのですか?例えばJavascriptの検索番号

"customer 92345678 and customer 9234" 

ありがとう!

+0

[regex](https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Regular_Expressions) '/ 9 \ d {1,8} /'を使用して、必要な処理を行うことができます。 – George

+0

正規表現を使用することができます:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions、http://www.regular-expressions.info/ –

+0

@Georgeは '/9 \ d {8}/' – GottZ

答えて

0

は、これは私のために動作します。

function f() 
{ 

var text = 'customer 92345678 and customer 9234'; 
var regex = /9\d{7}/g; 

var match = regex.exec(text); 

return(match[0]); 

} 

ありがとうございました。

1

あなたはRegular Expressionを使用して行うことができ、正規表現

var re = /9\d{7}/g; 
var str = 'customer 92345678 and customer 9234'; 
var myArray = str.match(re); 
console.log(myArray); 
+0

これはconsole.log、残念ながら、私はそれをサポートしていないプログラムに取り組んでいます。私はリターンを使用する必要があります。残念なことに、ここでリターンを使用すると、それはうまくいかず、アイデアはなぜですか? – Kayra

0

とexempleの下に見つけてください。

私はあなたが本当に長い文字列を持っていると仮定しています:

var str = 'customer92345678 customer12345678 customer1234 customer9234 customer98765432'; 

をあなたの質問によると、唯一のあなたは上記の例から検索しようとしている2つの有効な文字列があるはずです。

var arr = ['customer92345678', 'customer12345678', 'customer1234', 'customer9234', 'customer98765432']; 

アレイソリューション1からArray.prototype.filter()

:しかし String.prototype.match()

var searched = str.match(/\w{1,}9\d{7}/g); 

console.log(searched); // outputs ['customer92345678', 'customer98765432'] 

、あなたが(もっと論理的である)文字列の配列を持っている場合 -

文字列ソリューション

var searched = arr.filter(function(value){ return /9\d{7}/.test(value); }); console.log(searched); // outputs ['customer92345678', 'customer98765432'] 

アレイソリューション2からArray.prototype.forEach()

var searched = []; 

arr.forEach(function(value){ 
    if (!/9\d{7}/.test(value)) return; 
    searched.push(value); 
}); 

console.log(searched); // outputs ['customer92345678', 'customer98765432'] 

アレイソリューション3からfor loop

var searched = [], 
    len = arr.length, 
    i; 

for (i = 0; i < len; i++){ 
    if (!/9\d{7}/.test(arr[i])) continue; 
    searched.push(arr[i]); 
} 

console.log(searched); // outputs ['customer92345678', 'customer98765432'] 
+0

ありがとう、私は外部テキストファイルであるため、配列を使用していません。私は、文字列ソリューションは正常に動作するはずだと思うが、残念なことに私のプログラムはconsole.logを認識せず、 "コンソール"は定義されていないと言います。リターンで値を取得することは可能ですか? – Kayra

+0

ソリューションを使用して関数を作成し、戻り値を検索します。あなたの好奇心から、どのようなプログラムを使用していますか?これはWebベースのプロジェクトではありませんか? –

+0

ESKOという名前の会社のプログラムであるAutomation Engine用のスクリプトを使用しています。 – Kayra