2016-09-04 1 views
0

私は最後のインデックスマッチスペースで文字列から部分文字列を取得し、別の文字列に入れたい文字列1でvar string1="hello any body from me";javascriptの特定の文字に最後に見られた後に文字列から部分文字列を取得するには?たとえば ため</p> <p>私が持っている場合:

が、私は4つのスペースを持っていると私は言葉を取得したいですここで私は単語 "私"を取得したいと思います... 私はstring1のスペースの数を知りません...どのように私は最後にスペースのような特定のcharacerに見られた後に文字列から部分文字列を得ることができますか?

+1

[JavaScript文字列の最後のアンダースコアの前にテキストのみを返します](http://stackoverflow.com/questions/38208101/return-only-text-before-last-underscore-in-javascript-string) –

答えて

1

あなたはinputは、あなたの文字列ですsplit方法、使用して、このような何かを試みることができる:それを配列し、最後の要素を取得するために使用split

var splitted = input.split(' '); 
var s = splitted[splitted.length-1]; 

var splitted = "hello any body from me".split(' '); 
 
var s = splitted[splitted.length-1]; 
 
console.log(s);

+0

ok、それはあなたに大変感謝してくれます@Christos – sara

+0

@サラあなたは大歓迎です!私が助けてくれてうれしいです。 – Christos

1

を:

var arr = st.split(" "); // where string1 is st 
var result = arr[arr.length-1]; 
console.log(result); 
1

splitメソッドを使用すると、指定されたセパレータ(この場合は "")で文字列を分割し、返された配列の最後の部分文字列を取得できます。

これは、あなたが文字列の他の部分を使用したいと、それも読みやすい場合は良い方法です:

// setup your string 
 
var string1 = "hello any body from me"; 
 

 
// split your string into an array of substrings with the " " separator 
 
var splitString = string1.split(" "); 
 

 
// get the last substring from the array 
 
var lastSubstr = splitString[splitString.length - 1]; 
 

 
// this will log "me" 
 
console.log(lastSubstr); 
 

 
// ... 
 

 
// oh i now actually also need the first part of the string 
 
// i still have my splitString variable so i can use this again! 
 

 
// this will log "hello" 
 
console.log(splitString[0]);

これはなくても良い方法です部分文字列の残りの部分については、素早く汚れて書くことを好む場合:

// setup your string 
 
var string1 = "hello any body from me"; 
 

 
// split your string into an array of substrings with the " " separator, reverse it, and then select the first substring 
 
var lastSubstr = string1.split(" ").reverse()[0]; 
 

 
// this will log "me" 
 
console.log(lastSubstr);

1

それとも:メソッド

1

を逆にする

var string1 = "hello any body from me"; 
var result = string1.split(" ").reverse()[0]; 
console.log(result); // me 

感謝の私は、配列のオーバーヘッドを回避するために、正規表現を使用したい:

var string1 = "hello any body from me"; 
 
var matches = /\s(\S*)$/.exec(string1); 
 
if (matches) 
 
    console.log(matches[1]);

関連する問題