我怎样才能通过使用字符位置来获得单词

How can i get the word by using character position

本文关键字:位置 字符 单词      更新时间:2023-09-26

我有一个字符串,其中包含文本JavaScript And PHP。我得到了H字符的位置,即17。我已经得到了H的字符位置,但我现在想要的是得到在17位置有H字符的单词。使用java脚本/jQuery可以做到这一点吗。如果是,请帮我找出在17位置有一个字符的单词。

循环遍历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/

循环Before和After可以完成此任务。该代码使用

<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小提琴:http://jsfiddle.net/56a7711y/

我的想法

$('#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>