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
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.
var myString = textareaInput.split("\n").map(function(str){
return ' ' + str;
}).join("\n");
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>
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>
Related
Hello everybody I was trying to replace more than one string in an exercise for myself but I'm stucking with a regexp...
Since It's impossible to call two times replace I need to write a regexp to achieve my goal and I'm a noob with Regexp.
Basically I would like to write trace("Hello World"); and replace / remove trace("at start and ");" at the end of my String.
If I could use replace two times in a function it could be write as following statement :
<input type="text" id="input" onKeyUp="update()">
<p id="output"></p>
The script could be look like this:
function update(){
var x = document.getElementById("input").value;
if (x.startsWith("trace(\"") && x.endsWith("\");")){
document.getElementById("output").innerHTML = x.replace('trace(\"', '');
document.getElementById("output").innerHTML = x.replace('\");', '');
}else{
document.getElementById("output").innerHTML = "";
}
}
So till now my output is trace("Hello World or Hello World");if I comment the second replace statement.
The output should be Hello World with a correct Regexp I suppose.
Any help will be appreciate!
And sorry for my poor English.
Best regards.
Nicolas.
I hope the below answer is suitable for you.
x=x.replace('trace("', '');
function update(){
var x = document.getElementById("input").value;
if (x.startsWith("trace(\"") && x.endsWith("\");")){
x=x.replace('trace(\"', '');
document.getElementById("output").innerHTML = x.replace('\");', '');
}else{
document.getElementById("output").innerHTML = "";
}
}
<input type="text" id="input" onKeyUp="update()">
<p id="output"></p>
Thank you.
I currently load a value from my database straight into a hidden textarea.
<textarea name="text" id="text" style="visibility:hidden">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
</textarea>
From there I pick up the textarea's content and run it trough several replace arguments with a simple Javascript, like
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function parser() {
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\[size=1\]/g, "<span style=\"font-size:80%\">");
post_text=post_text.replace(/\[url=(.+?)\](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text=post_text.replace(/\[url\](.+?)\[\/url\]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
</script>
<div id="vorschau"></div>
to render it into HTML which is then parsed by the Browser, so I do all the formatting of the entries on the Frontend/client side.
However, the textarea may also contain such an UBB tag:
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
I currently just replace the textarea UBB elements like any other content
post_text=post_text.replace(/\[textarea\]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text=post_text.replace(/\[\/textarea\]/g, "</textarea>");
The issue with this is that my other code
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\</g, "<");
post_text=post_text.replace(/\>/g, ">");
Does not skip the content within the [textarea][/textarea] elements resulting in a textarea filled with this:
Content showing raw <b>HTML</b> or any other code<br>Including line breaks </a>
Above example
So how do I prevent to replace anything within [textarea][/textarea] (which can occur more than once in id="text")?
What you might do, is use a dynamic pattern that captures from [textarea] till [/textarea] in group 1, and use an alternation to match what you want to replace.
Then use a callback function for replace. Check if group 1 exists, and if it does return it unmodified. If it does not, we have a match outside of the text area.
An example of the pattern with the alternation and match for <
(\[textarea][^]*\[\/textarea])|<
(\[textarea][^]*\[\/textarea]) Capture group 1, match from [textarea] till [/textarea]
| Or
< Match literally
Regex demo
Note to double escape the backslash in the RegExp constructor.
(Assuming this is the right order of replacements:)
const replacer = (text, find, replace) => text.replace(
new RegExp(`(\\[textarea][^]*\\[\\/textarea])|${find}`, "g"),
(m, g1) => g1 ? g1 : replace
);
document.addEventListener('DOMContentLoaded', function parser() {
let post_text = document.getElementById('text').value;
post_text = post_text.replace(/\[size=1]/g, "<span style=\"font-size:80%\">");
post_text = post_text.replace(/\[url=(.+?)](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = post_text.replace(/\[url](.+?)\[\/url]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = replacer(post_text, "\\r?\\n", "<br>");
post_text = replacer(post_text, "<", "<");
post_text = replacer(post_text, ">", ">");
post_text = post_text.replace(/\[textarea]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text = post_text.replace(/\[\/textarea]/g, "</textarea>");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
<textarea name="text" id="text" rows="10" cols="60">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
< here and > here and
</textarea>
<div id="vorschau"></div>
I am using a third-party plugin for javascript called QueryBuilder.
The problem is there is no way to trim the input after saved so the data is being saved like
testName=' test '
this is my javascript code, which is removing all spaces which is not what I want, I am trying to remove just space in the single quotes before and after all the text. Pretty much like a trim but the trim is not working so I need a regex to replace method
get_condition_sql__str = $.trim(get_condition_sql.sql);
get_condition_sql__clean = get_condition_sql__str.replace(/\s/g, '')
console.log(get_condition_sql__clean);
jQuery('.exception_conditions__sql').val(get_condition_sql__clean);
Lookahead for exactly one ' before the end of the string:
const input = `testName=' test '`;
const cleaned = input.replace(/ +(?=[^']*'$)/g, '');
console.log(cleaned);
There's only one word in the input, but if you need to preserve spaces between words inside the quotes, alternate between matching a ' on either side of spaces instead:
const input = `testName=' test test2 '`;
const cleaned = input.replace(/' +| +'/g, "'");
console.log(cleaned);
Please use this one for left space remove:
<script type="text/javascript">
var original_str3 = " This is a string"
//Strips all space to the left of the string
alert( original_str3.trimLeft() + ' <--- Without any spaces on the left' );
</script>
Or use this one for right space remove:
<script type="text/javascript">
var original_str4 = "This is a string "
//Strips all space to the right of the string
alert( original_str4.trimRight() + ' <--- Without any spaces on the right' );
For Remove space from both side character or string:
<script type="text/javascript">
var original_str2 = "S t r in g"
//Strips excessive white spaces i.e. retains only one space between each letter
var white_space_stripped_str = original_str2.replace(/\s+/g, ' ');
alert(white_space_stripped_str + ' <---- With exactly one space between each letter in case each letter has multiple spaces');
</script>
If any other are required then please let me know.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">"vSourceCountry = 'TEST'"</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = `testName=' test test2 '`;
var res = str .replace(/' +| +'/g, "'");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Result:
Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:
testName='test test2'
Or You can use etc as per required:
https://www.w3schools.com/jsref/jsref_replace.asp
I want to find words which start with a specific letter in a string using the following code. The specific letter would be supplied by the user in a text box.
This is what I have:
<!DOCTYPE html>
<html>
<body>
<input id="srch" type="text" />
<button onClick=searchword()>Search</button>
<p id="wrd" > hallo, this is a test john doe .
Another tea house pole.
</p>
</body>
<script>
function searchword() {
var s = document.getElementById("wrd").innerHTML;
var p= document.getElementById("srch").value;
var regx = new RegExp("(?:^|\W)" + p + "(\w+)(?!\w)","gi");
var re = regx, match, matches = [];
while (match = re.exec(s)) {
matches.push(match[0]);
}
alert(matches);
}
</script>
</html>
You can use word boundaries \b, the following example shows how to match every word starting with t
var string ="hallo, this is a test john doe .Another tea house pole. Hey Tom."
result = string.match(/(\bt\S+\b)/ig);
//result = string.match(/(\st\S+)/ig); // alternative
document.write(result);
var string ="hallo, this is a test john doe .Another tea house pole. Hey
Tom."
result = string.match(/(\ba\S+\b)/ig);
document.write(result);
Let's say I have a text :
<p> hello world! </p>
and I am using a function that cut the text after 5 words and adds " ...show more"
I want the result to be like this :
hello ... show more
Because of the <p> tags what I get is this output :
hello ...show more
what I see when I inspect the element is this :
<p> hello </p> ...show more
I must mention that the text can be with <p> or without.
Is there a way to solve this problem ?
Is there a way to insert the added text inside the <p> tag ?
I need to mention that I need the <p> tags, I can't use strip tags function.
Thanks,
Yami
Do you mean this?
var text = "<p>hello world</p>";
var res = "<p>" + text.substring(3, 8) + " ...show more</p>";
It results in:
<p>hello ...show more</p>
The way I see it, you have two options:
.split() the string by spaces (assuming a space separates words) then slice the first (up to) 5 elements. If there are greater than 5 element, add "...read more"; if not, it's unnecessary.
You can use some regex replace and (with a negative lookahead) ignore the first 5 words, but replace all other text with your "...read more". (I personally find this one having more overhead, but you could probably use (?!(?:[^\b]+?[\b\s]+?){5})(.*)$ as a pattern)
Having said that, here's what i mean with a string split:
function readMore(el){
var ary = el.innerHTML.split(' ');
el.innerHTML = (ary.length > 5 ? ary.slice(0,5).join(' ') + '... read more' : ary.join(' '));
}
var p = document.getElementById('foo');
readMore(p);
Assuming of course, for the purposes of this demo, <p id="foo">Hello, world! How are you today?</p> (which would result in <p id="foo">Hello, world! How are you...read more</p>)
$('p').text($('p').text().replace('world!', '... show more'));