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]hello[/b]
[b]124[/b]
please help me :(
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]hello[/b]
[b]124[/b]
please help me :(
- 1 Ironically, the answer box is the answer.... – st0le Commented Dec 11, 2010 at 6:47
5 Answers
Reset to default 4text = 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;
Using only plain Javascript, you can do:
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:
var textArea = document.getElementById("yourTextAreaID");
textArea.value = "[b]" + textArea.value.split("\n").join("[/b]\n[b]") + "[/b]";
<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'))" />
- Convert the string into an array starting at position 1 of the array.
- Push the prefix at position 0 of the array.
- Convert the array back to a string with join.