lecham
lecham

Reputation: 2464

React highlight and slice long text

Let's image I have a long text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

I've entered letter s and a lot of letters of these text got highlighted. I want to slice it and show highlighted letters.

I use react-native-highlight-words to highlight the words. https://www.npmjs.com/package/react-native-highlight-words

In docs there's a sanitize method, but I'm not sure how can it be used? Sanitize - Process each search word and text to highlight before comparing (eg remove accents); signature (text: string): string

Here's the example:

enter image description here

Here's a piece of my code:

  <Highlighter
    highlightStyle={{ backgroundColor: 'yellow'}}
    searchWords={[searchWords]}
    textToHighlight={description}
  />

What's the best approach to achieve it?

Upvotes: 0

Views: 1124

Answers (1)

Pramod
Pramod

Reputation: 1940

From the above library (react-native-highlight-words) you will only highlight the text. But to get the highlighted character you will need to pull out the words using regex

Working Example: https://snack.expo.io/@msbot01/graceful-blueberries

import React, { Component } from 'react';
import { Text, View, StyleSheet, ScrollView, FlatList } from 'react-native';
import Constants from 'expo-constants';
import Highlighter from 'react-native-highlight-words';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      textSearch: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
      higightedTexts:''
    }
  }

  componentDidMount(){
    this.findSearchedText()

  }

  findSearchedText(){
    var regex = RegExp("s");
    var wordList = this.state.textSearch.split(" ").filter((elem, index)=>{
        return regex.test(elem);
    })

    this.setState({
      higightedTexts:wordList 
    })
  }

  viewForSearchedText(){
    var array = []
    for(var i=0; i<=this.state.higightedTexts.length; i++){
      var b = <View><Text>{this.state.higightedTexts[i]}</Text></View>
      array.push(b)
    }
    return array
  }






  render() {
    return (
      <View style={{ flex: 1 }}>
        <Highlighter
          highlightStyle={{backgroundColor: 'yellow'}}
          searchWords={['s']}
          textToHighlight= {this.state.textSearch}
        />
        <View>
          <Text style={{color:'green', marginTop:20}}>Higlighted Texts</Text>
          {
            this.viewForSearchedText()
          }
        </View>
      </View>
    );
  }
} 

const styles = StyleSheet.create({});

Upvotes: 1

Related Questions