2015-02-12 64 views
-1

我有一個字符串,其中包含文本JavaScript And PHP。我得到的H字符的位置是17。我已經得到了H的字符位置,但是我現在想要的是獲得在位置17處具有H字符的字。這是可能的Java腳本/ jQuery。如果是的話,請幫助我找到17處有一個字符的單詞。我怎樣才能通過使用字符位置

+0

字和字是不同的,如果你想這樣的事情再取字符啓動從17到空白空間來了,或者使用常規表達式 – 2015-02-12 09:10:52

+0

@ Arunprasanth KV可以從喲你的評論我發現它怎麼可能 – 2015-02-12 09:12:22

+0

@Hudixt這是否有幫助.. http://jsfiddle.net/d4tum8zy/ – 2015-02-12 09:18:45

回答

0

循環之前和之後可以做這個任務。該代碼是用來

<script> 
var string = "JavaScript And PHP"; 
var k = string.substr(0,17); 
     var n = k.split(" "); 

    var se = n[n.length - 1]; 

var ke = string.substr(17,string.length); 
var n = ke.split(" "); 
var see = n[0]; 
alert(se+see); 
</script> 

JS FIDDLE:http://jsfiddle.net/56a7711y/

1

通過H之前的字符循環,直到你到達一個空白處,然後從空白處開始循環(即PHP中的P)並遍歷該字直到你到達一個空間:)

var stringOld = "javascript and php"; 
var space = 0; 
for(x=17; x>0; x--){ 
if(stringOld [x] === " ") 
{ 
space = x; 
    break; 
} 
} 
for(y=space; y<stringOld.length; y++){ 
if((stringOld[y] === " ") ||(y=stringOld.length)) 
{ 
var newString = stringOld.slice(space,y); 
console.log(newString); 
    //alert(newString); 
} 
} 

的jsfiddle:http://jsfiddle.net/edrcfq8a/1/

+1

不工作的方式+1爲您的答案。我找到了答案,併發布 – 2015-02-12 09:30:41

+0

是的,我沒有測試過,一些變量iive輸入錯誤,現在試圖修復它在jsfiddle。 :))恭喜你自己排序;) – rekoDolph 2015-02-12 09:31:40

+0

加入JSFiddle:http://jsfiddle.net/edrcfq8a/ @Hudixt – rekoDolph 2015-02-12 09:40:16

0

我的想法

$('#check').on('click',function(){ 
 

 
var t = $('#text').val(); 
 
var a = t.split(' '); 
 

 
var pos = Number($('#positions').val()); 
 
var cha = $('#char').val(); 
 

 
$('#list').html(''); 
 
    
 
a.forEach(function(x){ 
 
    
 
    var $p = x.indexOf(cha,pos) 
 

 
     if(x.indexOf(cha,pos-1) == pos-1){ 
 
     
 
      $('#list').append('<li>"' + x + '" position of "' + cha +'" = ' + (x.indexOf(cha,pos-1) + 1) +'</li>'); 
 
     
 
     } 
 
    
 
}); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<textarea id="text" rows="4" cols="100">I have a string which contain the text JavaScript And PHP. I get the position of H character that is 17. I have get the character position of H but what i want now is to get the word which has H character at position 17. Is this possible with java script/jQuery. If yes please help me to get the word in which there is a character at position 17.</textarea> 
 

 
position : <input type="text" id="positions" value="5" /> <br/> 
 

 
char : <input type="text" id="char" value="h" /> <br/> 
 

 
<button id="check"> check word</button> 
 

 
<ul id=list> 
 
    <li></li> 
 
</ul>