Javascript:剪切字符串并返回不同的输入 [英] Javascript: cut string and return in different inputs
问题描述
我正在尝试在不同的部分剪切一个字符串,并将每个部分返回到不同的输入。以下是一个示例:
I'm trying to cut a string in different part, and return each part into a different input. Here's an example:
请考虑以下字符串: Hello | World |!
如您所见,有一个分隔符, |
。我想将 |
分隔的字符串的每个部分分开,并将它们返回到不同的输入中。
As you can see, there is a separator, which is |
. I'd like to separate each part of the string cut by this |
and return them into a different input.
我不能使用 str.substr()
(至少通常使用它,也许你有一个技巧)因为 |
之间的字符数不固定,有时它会是2个字符,有时是16个字符,而且据我所知 str.substr()
需要设置剪切前的字符数。
I can't use str.substr()
(at least the usual use of it, maybe you have a trick) because the number of characters between the |
is not fixed, sometimes it will be 2 characters, sometimes 16, and from what I know str.substr()
requires to set the number of characters before the cut.
基本上我正在寻找Excel中提供的解决方案,在转换功能中,您可以在其中定义分隔符,Excel会在每次找到分隔符集时将值的每个部分分隔为不同的单元格。
Basically I'm looking for a solution as Excel provides in the Convert feature, where you define a separator and Excel will separate each part of the value into different cells each times he finds the separator set.
这是Javascript的第一部分,取字符串粘贴的textarea的值:
This is the first part of the Javascript, taking the value of the textarea where the string is pasted:
function cutTheString()
{
var str = document.getElementById('textarea').value;
}
这就是HTML:
<textarea id="textarea"></textarea>
<br />
<input type="submit" value="Cut string" onClick="cutTheString()" />
<input type="text" id="string1"></input>
<input type="text" id="string2"></input>
<input type="text" id="string3"></input>
现在我有 document.getElementById('string1')。value = str();
将完整的字符串返回到第一个输入。我也可以使用 var res = str将分隔符
但这对我的情况没有帮助。 |
转换为,
.split(|);
For now I have document.getElementById('string1').value = str();
which returns the full string into the first input. I also have the possibility to transform the separator |
into ,
by using var res = str.split("|");
but that doesn't really help my case.
推荐答案
假设您有足够的< input>
元素:
function cutTheString()
{
var str = document.getElementById('textarea').value;
var arrayOfStrings = str.split('|');
for(var i = 0; i < arrayOfStrings.length; i++) {
document.getElementById("string" + (i+1)).value = arrayOfStrings[i];
}
}
参见 JS Fiddle 。
这篇关于Javascript:剪切字符串并返回不同的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!