我是编程新手,我想从某个位置替换字符串并将其替换为另一个字符串。
假设我有字符串“i am @hello”
。
我想替换从@开始到光标位置的字符串。
我有 @
字符和光标位置的索引,但我不知道如何使用替换方法来做到这一点。
下面是代码片段:
replace_string = (original_string, "someuser") => {
let new_value;
const string_to_cursor_position = original_string.substring(0,
this.state.cursor_position);
const at_char_position = string_to_cursor_position.lastIndexOf('@');
return this.value.replace(this.state.cursor_position,
value_selected);
}
但这不会替换字符串。最终输出应该是
“我是某个用户”
。
有人可以帮我解决这个问题吗?
最佳答案
您可以简单地使用替换及其回调
let replace_string = (original_string, replaceBy) => {
return original_string.replace(/@\w+/, replaceBy)
}
console.log(replace_string("i am @hello", 'someuser'))
我故意留下了g
标志,如果你想替换后面所有@
后面的字符串,你可以使用/@\w+/g
关于javascript - 如何使用javascript从某些位置删除字符串并在该位置添加另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754489/