使用string.split方法时如何保留字符
我正在使用string.split方法在array中添加项目。 这就是我的字符串的样子:
let modalMessage="Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"
我正在按“ /”字符进行分割,编辑,将字符串保存为新值并发送回服务器。此“ /”不保存。但是,当此“ /#****#/模板存在时,服务器会读取新值。如何解决此问题?
此处代码:
const App = ({ modalMessage }) => (
<p>
{modalMessage .split("/") .map(text => (
text.includes("#") ? <input value={text} /> : text
))}
</p>
);
答案 0 :(得分:0)
如果要保留斜杠/
,则可以使用包含捕获括号()
的正则表达式:
> let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back";
> let test = modalMessage.split(/(\/)/);
> test
(9) ["Hello, my name is ", "/", "# Ann #", "/", ". I'm working for ", "/", "# IStaff #", "/", ", could you please call me back"]
vs不带正则表达式:
> let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back";
> let test2 = modalMessage.split('/');
> test2
(5) ["Hello, my name is ", "# Ann #", ". I'm working for ", "# IStaff #", ", could you please call me back"]