IndexOf未在文本中查找字符串

时间:2014-12-23 11:43:51

标签: javascript jquery html

所以我的这个<p>包含用<span>包裹的字符,这些字符总共形成一个句子。现在我需要在<br/>的几个未知位置插入一些<p>,其中某些单词位于其中。为此,我写了一个函数:

function spaceInsert() {
    var sentence = [ 'spirit of brotherhood.' ];

    for( var i = 0; i < sentence.length; i++ ) {
      console.log( sentence[i] );
      console.log( $( '#body .tattoo-letters' ).text() );
      console.log( $( '#body .tattoo-letters' ).text().indexOf( sentence[i] ) );
    }
}

sentence数组包含需要断行的句子。为什么indexOf返回-1(未找到?)。我正在记录文本,它就在那里。

修改

控制台中的文本 - 第二个控制台日志(它是附加的,因此无法显示任何html)。 All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.Everyone is entitled to all the rights and freedoms set forth in this Declaration, without distinction of any kind, such as race, colour, sex, language, religion, political or other opinion, national or social origin, property, birth or other status. Furthermore, no distinction shall be made on the basis of the political, jurisdictional or international status of the country or territory to which a person belongs, whether it be independent, trust, non-self-governing or under any other limitation of sovereignty.

2 个答案:

答案 0 :(得分:1)

查看您的示例,以下内容有效:

$( '.tattoo-letters' ).text().indexOf('spirit\u00a0of\u00a0brotherhood.')

HTML中的空格是不间断的空格(U + 00A0)。

答案 1 :(得分:0)

试试我已在您的网站上查看

function spaceInsert() {
    var sentence = [ 'spirit of brotherhood.' ];

    for( var i = 0; i < sentence.length; i++ ) {
      console.log( sentence[i] );
      console.log( $( '#body .tattoo-letters' ).text() );
      console.log(  $("<div />").html($( '#body .tattoo-letters' ).text().trim()).html().replace(/&nbsp;/g," ").indexOf( sentence[i] )  );
    }
}
相关问题