Javascript 将字符串拆分为各种文本元素
我在顶部有一个搜索栏,结果被呈现到一个相当基本的列表视图中。我希望在搜索结果(字符串)中突出显示输入搜索栏(不区分大小写)的每个单词 目前,我做了一个基本的拆分:Javascript 将字符串拆分为各种文本元素,javascript,react-native,Javascript,React Native,我在顶部有一个搜索栏,结果被呈现到一个相当基本的列表视图中。我希望在搜索结果(字符串)中突出显示输入搜索栏(不区分大小写)的每个单词 目前,我做了一个基本的拆分: let split = question.title.split(this.state.searchInput); 并将其呈现给: <Text style={styles.title}> {split[0]} </Text> {split.length > 1 ? <View sty
let split = question.title.split(this.state.searchInput);
并将其呈现给:
<Text style={styles.title}>
{split[0]}
</Text>
{split.length > 1 ?
<View style={{flexDirection: 'row'}}>
<Text style={styles.fatTextResult}>
{this.state.searchInput}
</Text>
<Text style={styles.title}>
{split[1]}
</Text>
</View>
:
null
}
{split[0]}
{split.length>1?
{this.state.searchInput}
{split[1]}
:
无效的
}
在搜索结果中键入两个未连接的单词时,此拆分显然不起作用。我怎样才能做到这一点
看起来是这样的
试试这个:
highlightWord( word , search ){
var newWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
if ( search.toLowerCase().indexOf(newWord.toLowerCase()) != -1 ){ // if word in question
// highlight it
return <Text style={{fontWeight:'bold'}}>{word}</Text>
}
else{
return <Text>{word}</Text>
}
}
renderRow( question ){
let split = question.title.split(' '); //divide question in words
textViews = [];
for (var i=0 ; i<split.length ; i++){
var word = split[i]; // get words
textViews.push( highlightWord(word,this.state.searchInput) );
}
// return all words together (highlighted or not)
return <View style={{flexDirection:'row'}}>{ textViews }</View>
}
highlightWord(单词,搜索){
var newWord=word.replace(/[,\/\\\!$%\^&\*;:{}=\-\\-\\`~()]/g,“”;
if(search.toLowerCase().indexOf(newWord.toLowerCase())!=-1){//if有问题的单词
//突出显示它
返回{word}
}
否则{
返回{word}
}
}
伦德罗(问题){
让split=question.title.split(“”);//用文字来划分问题
textViews=[];
对于(var i=0;我认为这是可行的,但不适用于以标点符号结尾的单词……有什么想法吗?