V
V
Vladimir2020-11-22 04:08:02
React
Vladimir, 2020-11-22 04:08:02

How to replace selected text in input with an addition to it?

Good evening. I am making an editor, when selecting, I need to replace, say, MY TEXT with MY TEXT2, I was able to do this, but the problem is that if there are 2 or 3 such phrases, then it takes the first match. I do not understand how to implement this through getSelection and work with the selected area itself. How to replace the selected phrase, and not the first match?

import {url} from "../../serverConfig";
import GetTextEditor from "../lowLvlComponents/textEditor/textEditor";
import styles from '../../pages/css/articles/createArticle.module.css';
import { useState } from 'react';


export default function CreateArticle() {

    const [input, setInput] = useState();
    const [data, setData] = useState();

    return (
        <div className={styles.createArticle}>
            <div className={styles.title} onClick={() => input.value =
                input.value.replace(
                    data, `<b>${data}</b>`
                )}>Новая статья</div>
            <form action={`${url}/createArticle`}>
                <input type="text" placeholder={'Название'} onSelect={() => 
                    setData(document.getSelection().toString())
                } onClick={(e) => 
                    setInput(e.target)} onMouseDown={() => false}/>
                <input type="text" placeholder={'Ссылка на превью-картинку'} />
                <input type="text" placeholder={'Превью-текст'} />
                <GetTextEditor />
                <div className={styles.submitBox}>
                    <button>Создать</button>
                </div>
            </form>
        </div>
    )

}


Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2020-11-22
@WblCHA

This is not serious, there is a solution to this problem right in the documentation...
https://developer.mozilla.org/ru/docs/Web/API/Sele...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question