This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}
Related
I've tried this
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
var mySte = myStr.textContent;
console.log(mySte);
</script>
</body>
and I want this following outcome
just some random text
random text
You can use this regex to find and replace string without breaking html: /(?!<[^>]+)\.(?![^<]+>)/g
[myattr]
{
background-color: pink;
}
[myattr]:after
{
content: "this element's attribute is: " attr(myattr);
background-color: lightgreen;
margin: 1em;
}
p > span
{
background-color: lightblue;
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some. random text. <span myattr="text.with.dots">nested.html</span> end.
<span>i < 40. But i is also > 30. What are valid values of i?</span>
</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
myStr.innerHTML = myStr.innerHTML.replace(/(?!<[^>]+)\.(?![^<]+>)/g, "<br>");
console.log(myStr.innerHTML);
}
</script>
</body>
To directly answer the question:
var outputHtml = inputText.replace(/\./g, '<br />');
The Javascript replace method will by default replace the first instance of something (the first . in this case), so the g regex modifier tells it to replace them all. The \. in the regex is because . is a special character in regexes. This will replace every dot in the text.
What about ellipsis?
This technique won't work well on text that contains literal ellipsis, like this:
Hello world...
If your text is likely to contain this, and you want that to be ignored, then the following regex is more appropriate:
/[^\.](\.)[^\.]/g
This'll match any . which is not surrounded by other .
var outputHtml = inputText.replace(/[^\.](\.)[^\.]/g, '<br />');
Handling HTML
In the question here, the input is actually coming from the DOM. We can't replace . on its innerHTML as it would replace content inside HTML tags as well. So, if your input text is coming from the DOM like this (and not, say, a textarea), then the safest route is to apply the replacement only to text nodes. That is done like this:
document.getElementById("start").addEventListener("click", () => {
var inputNode = document.getElementById("text");
replace(inputNode);
});
function replace(node) {
if(!node) {
return;
}
if (node.nodeName == '#text') {
// We've found a text node. Apply the regex to it now.
// Note that you can use either of the above regexes here.
var inputText = node.textContent;
var lines = inputText.split(/\./g);
if(lines.length > 1) {
// It had at least one dot in it.
// Swap in this new set, each with a <br /> between them.
var parent = node.parentNode;
var nextSibling = node.nextSibling;
parent.removeChild(node);
lines.forEach((line, i) => {
if(i != 0){
// insert the <br>
var br = document.createElement('br');
parent.insertBefore(br, nextSibling);
}
var textNode = document.createTextNode(line);
parent.insertBefore(textNode, nextSibling);
});
}
} else {
// Loop through each child node.
// We go backwards such that completed replacements don't affect the loop.
for(var i=node.childNodes.length - 1; i>=0; i--) {
replace(node.childNodes[i]);
}
}
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" id="start">Replace</button>
</body>
</html>
If you're starting from a HTML string inside a browser, you can then use the above replace method and the browsers internal parsing to safely only affect the actual text:
function replaceHtmlString(html) {
var div = document.createElement('div');
div.innerHTML = html;
replace(div);
return div.innerHTML;
}
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
I have a paragraph from which i want to delete a complete one string when user press single backspace.
For example like in yahoo mail. when we compose an email and write email address at "To or CC or BCC" section(s), when user press single backspace the complete email address is deleted.
I want that functionality but in paragraph.
Removing e-mail addresses on backspace is just a deletion of characters until you hit a space (or ; depends on your use case) char.
So basically what you are really asking here is:
How to substring the last portion of a string while the space character is the delimiter.
Here is a simple snippet as example:
EDIT:
I've updated the snippet to support caret (cursor) position while clicking the backspace or delete keys.
$('#delete').on('click', function(){
var $input = $('#mystring');
var nextStr = deleteUpToSpace($input.val());
$input.val(nextStr);
});
$('#mystring').on('keyup', function(e){
var currentCursorPoisitoin = this.selectionStart;
if(e.keyCode == 8 || e.keyCode == 46){ // backspace or delete keys
var $input = $(this);
var nextStr = deleteBasedOnPosition($input.val(), currentCursorPoisitoin);
$input.val(nextStr);
}
});
function deleteUpToSpace(str){
var index = str.lastIndexOf(" ");
var nextStr = str.substring(0, index);
return nextStr;
}
function deleteBasedOnPosition(str, position){
var strUpToPosition = str.slice(0, position);
var lastIndexOfSpace = strUpToPosition.lastIndexOf(" ");
var strToRemove = strUpToPosition.substring(lastIndexOfSpace, position);
var nextStr = str.replace(strToRemove, "");
return nextStr;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mystring" value="this is a test string">
<button id="delete">Delete</button>
You probably want to remove a word when backspace is clicked.
You can use this code.
<!doctype html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>
<textarea id="foo"></textarea>
<script type="text/javascript">
document.getElementById('foo').addEventListener("keydown",function(event){
if(event.code=="Backspace"){
var text=document.getElementById('foo').value;
var lastspace = text.lastIndexOf(" ");
var updateStr=text.substring(0,lastspace);
document.getElementById('foo').value=updateStr;
}
});
</script>
</body>
</html>
Firstly, you need to identify the separator that separates these different entities. For instance, if you need to remove the last sentence in a paragraph, the separator is the period (or full-stop, as some may call it).
Then, you can split the string by the separator, remove the last two elements (because the last element is essentially a non-completed) and then rejoin.
text.split('.').slice(0,-2).join('.') + '.'
If your separator was a period. Or generally,
text.split(separator).slice(0,-2).join(separator) + separator
See this JS Fiddle I made for demonstration: https://jsfiddle.net/tt24kfng/1/
An interesting thing you could try out would be to remove the last completed entity and keeping the last incompleted intact.
I want to append the given string to the textarea i have, i want to append the text in the way it should look like someone typing on the texture,because i have the voice playing in the background for 6 seconds which which says the same thing to be written.
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
<script>
function addText(event) {
document.getElementById("typeable").value += "Hello welcome to the new world of javascript"
}
</script>
how can i do this
Count the number of characters in the sentence, and then calculate the time for each char by dividing the total time with the no. of characters and then call the time Interval and run it until all the characters are printed.
Still you can decide the time taken to print each character and modify it as per your need. Please note that the time is taken in milliseconds.
var chars = "Hello welcome to the new world of javascript".split("");
var textarea = document.querySelector('textarea');
var total_time=6000;
var index = 0;
var time_per_char = total_time/chars.length;
var t = setInterval(function(){
textarea.value += chars[index];
index++;
if (index === chars.length){
clearInterval(t);
}
},time_per_char);
<textarea style="width:100%;background:#E1ECF4">
</textarea>
Code is attached below:
<!DOCTYPE html>
<html>
<script>
function appendText() {
document.getElementById("typeable").value= document.getElementById("typeable").value + "Hello welcome to the new world of javascript";
}
</script>
<body onload="appendText()">
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
</body>
</html>
I am in need of your assistance,
What I need is a javscript function that would accomplish one of two things:
Firstly, if given a string, ie. var x = "filenumber" the function when called, would process the string and add a -2 to the end of it, resulting in var x = "filenumber-2" if the -2 does not exist on the end of the string.
Secondly, if the given value, var x is already = "filenumber-2" then take the number at the end of the string and increment it by 1, resulting in var x = "filenumber-3". and so fourth incrementing the number every single time after that, if the function is called again.
Here is the concept markup:
<DOCYTPE HTML>
<html>
<head>
<script type="text/javascript">
function test(){
var x = document.getElementById('input').value
1.) if x doesnt already have the -2 at the end of the string then add it:
document.getElementById('output').value = x + "-2"
2.) else, the function recognizes that it does and the result of the output is
x-2 + 1
}
</script>
</head>
<body>
<input type="text" id="input"/>
<br>
<input type="text" id="output"/>
<br>
<input type="button" onclick="test()" value="test"/>
</body>
</html>
Short 'n sweet:
x = 'filenumber-4';
x = x.replace(/^(.+?)(-\d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );