简体   繁体   English

如何使用javascript为每行文本添加前缀/后缀?

[英]How to add a prefix/suffix to text per line using javascript?

how would i add a prefix per line to a text area.. example:我如何将每行的前缀添加到文本区域.. 示例:

this is the content of the textarea:这是文本区域的内容:

hello
124


and i would want to add a [b] prefix and suffix to each line so that when i click a button the result will be:我想为每一行添加一个 [b] 前缀和后缀,这样当我单击一个按钮时,结果将是:


[b]hello[/b]
[b]124[/b]


please help me :(请帮我 :(

Using only plain Javascript, you can do:仅使用纯 Javascript,您可以执行以下操作:

var textArea = document.getElementById("yourTextAreaID");
var lines = textArea.value.split("\n");
for (var i = 0; i < lines.length; ++i) {
    lines[i] = "[b]" + lines[i] + "[/b]";
}
textArea.value = lines.join("\n");

Or, as @Alin Purcaru suggested, without using a loop:或者,正如@Alin Purcaru 建议的那样,不使用循环:

var textArea = document.getElementById("yourTextAreaID");
textArea.value = "[b]" + textArea.value.split("\n").join("[/b]\n[b]") + "[/b]";
text = document.getElementById("the_textarea").value;
document.getElementById("the_textarea").value = text.replace(/.+/g, "[b]$&[/b]");

Example:例子:

替代文字

using joins and splits:使用连接和拆分:

var prefix = '[b]', suffix = '[/b]',
   txt = document.getElementById('myText');
txt.value = prefix + txt.value.split('\n').join(suffix + '\n' + prefix) + suffix;
<script language="javascript" type="text/javascript">
function TextDefine(val){
var i= 0;                

var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; i++) {
    array1[i] = "[b]" + array1[i] + "[/b]";
}
val.value = array1.join("\n");

}
</script>

<textarea name="data" id="data"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'))" />
  1. Convert the string into an array starting at position 1 of the array.将字符串转换为从数组位置 1 开始的数组。
  2. Push the prefix at position 0 of the array.将前缀推送到数组的位置 0。
  3. Convert the array back to a string with join.使用连接将数组转换回字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM