gpt4 book ai didi

php - 在 JavaScript 和 PHP 中用逗号\换行分割字符串

转载 作者:行者123 更新时间:2023-11-29 20:08:20 27 4
gpt4 key购买 nike

这让我发疯。我有一个 PHP 脚本,它从 MySQL 获取一些数据并将其保存为一个字符串,其中元素以逗号分隔。

JavaScript 获取该字符串并将逗号替换为“\n”并将其显示在文本区域内。现在,我可以从文本区域向文本添加新行。单击按钮时,字符串应转换回以逗号分隔的元素,然后再次设置为 PHP(通过 AJAX),以进行保存。问题在于 JavaScript,当文本区域中的行数超过 3 行时,它无法检测到 '\n' 字符。

// These are the lines of the text-area, after replacing ',' by '\n'
var textarealines=input_hidden_element.value.replace(',','\n').replace(',','\n');

// When trying to replace '\n' by ',' and send back, PROBLEM!
var AjaxRequest = WT.AjaxObject();
AjaxRequest.open('POST', WT.AjaxLocation, true);
AjaxRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AjaxRequest.send('values=' + textarealines.replace('\n', ',').replace('\n', ','));
AjaxRequest.onreadystatechange = function() {
// Bla bla bla
}

那么,我做错了什么?最多两行,新行被逗号正确替换,但是当我添加超过 2 行时,只有前 2 行被替换,接下来的行与 'n' 字符一起发送,作为包含 '\n' 的单行文本。谢谢

最佳答案

尝试添加全局搜索标志:

textarealines.replace(/\n/g, ',')

请注意,/\n/g 不是单引号,这意味着它是一个 regular expression .

类似地,要从换行到逗号,请尝试:

input_hidden_element.value.replace(/,/g, '\n')

这个问题类似于"How to replace all points in a string in JavaScript."

关于php - 在 JavaScript 和 PHP 中用逗号\换行分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11155634/

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