我有一个包含文字JavaScript And PHP
的字符串。我得到H
字符17
的位置。我已经获得了H的角色位置,但我现在想要的是获得在17
位置具有H字符的单词。这可能与java脚本/ jQuery。如果是,请帮助我获取位置17
中有字符的单词。
答案 0 :(得分: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 :(得分: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/
答案 2 :(得分: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>');
}
});
});
&#13;
<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>
&#13;