gpt4 book ai didi

javascript,拆分字符串并显示一个单词粗体

转载 作者:行者123 更新时间:2023-11-29 23:59:26 28 4
gpt4 key购买 nike

我有一个包含单词索引的字符串,我想将其显示为粗体。

this.splitSentence(exercise.sentence,boldWordIndex)

所以我决定将字符串分成三部分;在 boldWord 之前、boldWord 之后。所以我将函数定义如下。但我在加入时遇到问题,中间的 3 个单词没有空格。而且我认为应该有更好的方法。

splitedSentence(sentence,index) {
var splitedSentece = sentence.split(" ");
var slice1=splitedSentece.slice(0,index);
var slice2=splitedSentece.slice(index,index+1);
var slice3=splitedSentece.slice(index+1,splitedSentece.length);
return [slice1.join(" "),slice2.join(" "),slice3.join(" ")];
}

天啊!我在 React 应用程序中写这个

最佳答案

希望这就是您要找的>> fiddle :

class Example extends React.Component {
constructor(){
super();
this.state = {
word: ''
}
this.change = this.change.bind(this) ;
}
change(e){
this.setState({ [e.target.name]: e.target.value});
}
render(){
const index = this.props.sentences.split(' ').indexOf(this.state.word);
const sentences = this.props.sentences.split(' ').map((item, key) => {
// index may come from server
return <Word classN={index === key ? 'foo' : ''} key={key} text={item} />
});

return <div>
<input name='word' type='text' onChange={this.change}/> <br/>
{sentences}
</div>
}
}

class Word extends React.Component {
render(){
return <span className={this.props.classN}>{` ${this.props.text} `}</span>
}
}

React.render(<Example sentences={'Hello World from ReactJS'}/>, document.getElementById('container'));

关于javascript,拆分字符串并显示一个单词粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40969960/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com