Multiple String Manipulation using js - javascript

I have a text area that I will paste some data in for example like so
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
And when I click submit all the text inside the text box to give an output below something like this
06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019
I have managed to this on python using this code
filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
for line in fp:
line = line.strip('\n')
new = line.split("-")
f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()
I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery

You can register an onsubmit listener on your form and then in the handler, perform your logic of parsing the text area's value.
The following snippet is an example of how to do that:
// Register 'submit' event listener
document.querySelector('#form')
.addEventListener('submit', e => {
// Prevent default action so that page doesn't refresh
e.preventDefault();
// Get the text from the textarea
let text = document.querySelector('#text').value;
// Split the lines
let converted = text.split('\n')
// Convert each line
.map(str => {
// Extract the date parts
let [mm, dd, yyyy] = str.split('-');
// Return the desired format by joining the date parts with /
return [dd, mm, yyyy].join('/');
});
// Print result to console
console.log(converted);
});
<form id="form">
<textarea id="text"></textarea>
<button type="submit">submit</button>
</form>

use following regexp-replace for textarea value
value.replace(/(-)(?=\d)/g,'/')
The (-)(?=\d) will find all dashes '-' preceding the number
function submit() {
let r=data.value.replace(/(-)(?=\d)/g,'/');
console.log(r);
}
textarea { width: 200px; height: 100px; }
button { display: block }
<textarea id="data">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>
<button onclick=submit()>Submit</button>

You don't really need any jQuery for this just a little regex should work.
const datesArr = [
'01-06-2019',
'01-07-2019',
'01-08-2019',
'01-09-2019',
'01-10-2019',
]
const newDates = []
const regex = /(\d\d)-(\d\d)-(\d{4})/
for (let date of datesArr) {
newDates.push(date.replace(regex, '$2/$1/$3'))
}
console.log(newDates)

function convertToFormat(data) {
var _dataSplit = data.split('\r\n');
var _length = _dataSplit.length;
var _finalData = '';
for (var i=0;i<_length;i++) {
var _dataDSplit = _dataSplit[i].split('-');
_finalData += _dataDSplit[1]+'/'+_dataDSplit[0]+'/'+_dataDSplit[2]+'\r\n';
}
return _finalData;
}

You can get the text area value on clicking submit like the below snippet. You can do your date manipulation (Learn some string manipulation to do the formatting. Refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
function formatText() {
var textAreaValue = $('#my-text').val();
// Do the necessary formatting here
var formattedText = 'test';
$('#my-text').val(formattedText);
}
.btn {
display: block;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="my-text"></textarea>
<button class="btn" onClick="formatText()">Submit</button>
</div>

Try using regex replace.
Regex demo here
let dates = document.getElementById('dates');
console.log(dates.value.replace(/(\d{2})-(\d{2})-(\d{4})/g, '$2/$1/$3'))
<textarea id="dates" rows="6" cols="30">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>

Related

Copy the result of a function to the clipboard

Can someone tell me how to copy the result of a function to the clipboard?
After copying the result to the clipboard, I want to paste it after clearing the textarea.
function strReplace() {
var myStr = document.getElementById("source").value;
var newStr = myStr.replace(/&‌#‌1084‌;/g, "м")
.replace(/&‌quot‌;/g, '"');
if(document.getElementById("source").value == '') {
alert("Textarea is empty!");
return false;
} else {
// Insert modified string in paragraph
document.getElementById("myText").innerHTML = newStr;
taErase();
document.getElementById('button').focus();
}
}
Use this function and pass the value is to be copied as it's only argument.
function copyText (copyText = null){
let textArea = document.createElement("textarea")
textArea.value = copyText
textArea.style.position = "fixed"
textArea.style.left = "-999999px"
textArea.style.top = "-999999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((res, rej) => {
document.execCommand('copy') ? res() : rej()
textArea.remove()
//alert('Text Copied!')
})
}
I did some changes in your code to simulate a functional example:
Auxiliary function copyToClipboard to copy element value to clipboard
Auxiliary function getSource() to generate a source if is empty
Auxiliary function start() trigger the process manually
When the page finish load, the code will:
Check if textarea is empty and print in console (before was an alert)
Now press start button to init process and check if has something in source input
If hasn't any text in source input or is empty, generate one
When has an text in source input:
replace special chars
copy to clipboard
copy to textarea
focus the Click Me! button
Added a css background to change the button color to see the focus (Optional)
Some functions isn't necessary in your solution, just used it to build a functional example.
Good pratices:
Choose one possibility: In your code or use double quote " or single quote '
When post the problem try to post a functional exemple not just a part of code
Follow an example based on your question:
function strReplace() {
let source = document.getElementById("source");
let myStr = source.value;
let newStr = myStr.replace(/&‌#‌1084‌;/g, "м")
.replace(/&‌quot‌;/g, """);
if (myStr == "") {
console.log("Textarea is empty!");
} else {
copyToClipboard(source);
document.getElementById("myText").innerHTML = newStr;
document.getElementById("button").focus();
}
}
function getSource() {
let source = document.getElementById("source");
if (!source.value) {
source.value = "<!DOCTYPE html><html><head><title>Page Title</title></head>" +
"<body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
}
}
function start() {
getSource();
strReplace();
}
function copyToClipboard(element) {
element.select();
document.execCommand("copy");
console.log("Text copied to clipboad:\n" + element.value);
}
strReplace();
#button:focus {
background: yellowgreen;
}
#source {
min-width: 260px;
}
#myText {
min-height: 130px;
min-width: 260px;
}
<div>
<input id="source" placeholder="Source">
<button id="start" type="button" onclick="start()">Start</button>
</div>
<hr>
<div>
<textarea id="myText"></textarea>
</div>
<div>
<button id="button" type="button" onclick="strReplace()">Click Me!</button>
</div>

Display <textarea> content in <div>

I'm really new to Javascript. I am trying to output the current date and also the content in the textarea tag in HTML on button click.
However I do not know how to obtain the content when the textarea is not declared along with a name/id/class.
Here's my code:
<script>
function displayPost() {
var thisDiv = document.getElementById("posts");
var date = new Date();
date.classList.add("post-time");
var textarea = document.getElementByTagName("textarea");
textarea.classList.add("post-content");
thisDiv.innerHTML = date + textarea;
}
</script>
<html>
<div id="posts"></div>
<textarea rows="4" cols="60">Type your text here...</textarea>
<button onclick = "displayPost()">Post</button>
</html>
Any sort of help is appreciated! Thank you in advance!
You can use document.querySelector when a dom element does have any name/id/class like:
var textarea = document.querySelector('textarea');
To get the current date in a readable format, you can use toLocaleString() method:
var date = new Date();
console.log(date.toLocaleString());
// → "3/21/2020, 7:00:00 PM"
To get <textarea> current entered value you can use:
var textarea = document.querySelector('textarea');
console.log(textarea.value);
DEMO:
function displayPost() {
var thisDiv = document.getElementById('posts');
var date = new Date();
thisDiv.classList.add("post-time");
var textarea = document.querySelector('textarea');
textarea.classList.add("post-content");
thisDiv.innerHTML = date.toLocaleString() + ': '+ textarea.value;
}
.post-time{padding:20px 0}
<div id="posts"></div>
<textarea rows="4" cols="60" placeholder="Type your text here..."></textarea>
<button onclick="displayPost()">Post</button>
you can make use of document.querySelector() which returns first matching element or document.getElementsByTagName() which returns NodeList of all the textarea elements
var textarea = document.querySelector('textarea').value;
or
var textarea = document.getElementsByTagName('textarea')[0].value;

Modifying URL with javascript

I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix

How to replace a text with coloured text using javascript

I am having this text in text area.
{color:#c91d1d}Hello{color}
when it is submitted, i want the text between {} tags to be shown in color specified inside {} tag with color:
how can i do so in javascript
use javascript built in function to extract color code
var colorValue = str.substring(7, 7);
it extract 7 characters from 7th position.
now change the color using:
document.getElementById("myH2").style.color = colorValue;
I hope this will work
You can use a regex like
$('#input').on('input', function() {
$('#result').html(this.value.replace(/\{color:(.*?)\}(.*?)((\{color\})|$)/g, '<span style="color:$1">$2</span>'));
}).triggerHandler('input');
textarea {
width: 100%;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="input">{color:#c91d1d}Hello{color} - {color:green}hi{color}</textarea>
<div id="result"></div>
Arun is right, and if you just need to get "Hello" from "{color:#c91d1d}Hello{color}" string you can do it like this
var justtext="{color:#c91d1d}Hello{color}".match(/\{.*\}(.*)\{.*\}/)[1];
For full replacement of text in textarea here's the code. Suppose textarea has id attribute "textarea1", change it with your id.
var textwithcolor =$("#textarea1").text();
var justtext=textwithcolor.match(/\{.*\}(.*)\{.*\}/)[1];
$("#textarea1").text(justtext);
this is how it can be done
No need to use regular expressions.
try this
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("{color}") > -1) {
newstr = newstr.replace("{color}", "</div>");
}
while (newstr.indexOf("{color:") > -1) {
newstr = newstr.replace("{color:", "<div style='color:");
newstr = newstr.replace("}", "'>");
}
document.getElementById("t").innerHTML = newstr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">{color:#c91d1d}Hello{color}
{color:red}How{color} {color:yellow}are{color} {color:green}you{color}
</div>

Add a span tag to certain characters in a string with javascript/jquery

I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:
<div class="date">12 // 14 // 2013</div>
How can I add:
<span style="slashColor">
to the two double slashes so that my result would be:
<div class="date">12 <span class="slashColor">//</span> 14 <span class="slashColor">//</span> 2013</div>
Try this:
var original = $('.date').text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$('.date').html(new_version);
Fiddle
If you have many div like the example you posted, you can use this:
$('.date').each(function () {
var original = $(this).text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$(this).html(new_version)
});
Fiddle
var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
e.innerHTML = e.innerHTML.replace(/\/\//g, '<span class="slashColor">//</span>');
}
or the jQuery way:
$('.date').each(function () {
$(this).html($(this).html().replace(/\/\//g, '<span class="slashColor">//</span>'));
}

Categories

Resources