-3

I'm trying to bold the text in the first occurence of string, matching the input query but the character is getting bold on every occurence in the string.

Input : "9"
Current Output:9989459
Expected output:9989459

 var  display = "9989459" 
 var input = "9"
 var splitArr = display.split(new RegExp(`(${input})`, 'gi'));
 var result =  splitArr.map((parts,i) => parts === input ? <b key={i}>{parts}</b> : parts)
 return <span> {result} </span>
6
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 20, 2021 at 18:28
  • @WiktorStribiżew - The <b> is JSX and not a string. Commented Jan 20, 2021 at 18:31
  • If i use that delimiter , the characters after that are not present in a array Commented Jan 20, 2021 at 18:32
  • @WiktorStribiżew I tried that it's rendering with that bold tag wrapping around the search query , like <b>9</b>989459 Commented Jan 20, 2021 at 18:34
  • Ok, try var rx = new RegExp(`(${input})`, 'gi'); var splitArr = display.split(rx, 2); splitArr.push( display.substr(rx.lastIndex + splitArr.join("").length) ) Commented Jan 20, 2021 at 18:40

1 Answer 1

-2
const target = '9'
const str = '9989459'
const index = str.indexOf(target)

const parts = [a.slice(0, index), `<b>${a.slice(index, index+1 )}</b>`, a.slice(index + 1)]

// [ '', '<b>9</b>', '989459' ]
Sign up to request clarification or add additional context in comments.

2 Comments

No, Its rendering with that b tag , like <b>9</b>989459
Yes, this is just the example code to extract and transform the original string. Use the resulting array as you wish, for instance to generate html in directly or with any framework

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.