Reputation: 2735
My Input is:
hello world one
hello world two
hello world three
I have tried so far:
$('.insertSpace').click(function(event) {
var textareaInput=$('.textareaInput').val();
var myString = ' ' + textareaInput.split();
$('.textareaInput').val(myString);
//console.log(myString);
});
It is working for just first sentence.I want to insert space in every sentence. Where is the fault in my code?
Its output should look like this:
hello world one
hello world two
hello world three
Upvotes: 0
Views: 1063
Reputation: 18888
You can create a simple regex if you use the m
modifier (which matches on a multi-line basis)
function addSpaces() {
var textarea = document.querySelector('textarea');
textarea.value = textarea.value.replace(/^(.)/gm, ' $1');
}
<textarea id="text">
hello world one
hello world two
hello world three
</textarea>
<button onclick="addSpaces()">Add Spaces</button>
However, if you also want to normalize spaces you can swap out that regex for this:
.replace(/^(?!\n)(\s*)(.)/gm, ' $2');
which will remove tabs, or pre-existing spaces and only add 1 space no matter how many times you run that function. It will leave new lines alone.
Upvotes: 3
Reputation: 3856
If the desired outcome is to move/indent the text to the right you can just use padding:
.indent {
/* Indent with as much you as like to */
padding-left: 1rem;
}
<textarea class="indent" cols="20" rows="5">
Some text
Hello world
Winter's coming
</textarea>
Upvotes: -1
Reputation: 6652
var myString = textareaInput.split("\n").map(function(str){
return ' ' + str;
}).join("\n");
Upvotes: 2
Reputation: 1074138
I think by "sentence" you mean line. If so, you can use replace
with a regular expression to do that. Example:
var textareaInput = $('.textareaInput').val();
var myString = " " + textareaInput.replace(/(\r?\n)/g, "$1 ");
$('.textareaInput').val(myString);
Live copy:
$('.insertSpace').click(function(event) {
var textareaInput = $('.textareaInput').val();
var myString = " " + textareaInput.replace(/(\r?\n)/g, "$1 ");
$('.textareaInput').val(myString);
});
<textarea class="textareaInput" cols="20" rows="5">
hello world one
hello world two
hello world three
</textarea>
<input type="button" class="insertSpace" value="Insert Space">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 1