How to add a prefix/suffix to text per line using javascript? - javascript

how would i add a prefix per line to a text area.. example:
this is the content of the textarea:
hello124
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 :(

text = 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.

Related

How to find a particular value in a string in js

I have a data like this,
var str = "#data time #city";
My goal is to make this as
var str = <a src="www.test/data">#data</a> time <a src="www.test/city">city</a>
I mean in my string where ever I found # its next value i.e data should be set as a param to the link www.test/{{param}} and should be surrounded with a link.Can any one suggest help.Thanks.
For this case, the String.replace() function will help you:
var str = "#data time #city"
str = str.replace(/#(\S+)/g, '#$1')
output.textContent = str
clickable.innerHTML = str
#output { font-family: courier }
<div id="output"></div>
<div id="clickable"></div>
The following code converts you data to the expected output.
The document.write(..) are for debug.
var data='#data time #city';
var hashtags = data.match(/#\S+/g);
document.write('before: ' + data + '</br>');
for (j = 0; j < hashtags.length; j++) {
// remove # from hashtag
var tag = hashtags[j].substring(1, hashtags[j].length);
// create the link
var link = '< a src="www.test/' + tag + '>#' + tag + '< / a > ';
// replace hashtag with link
data=data.replace(hashtags[j], link);
}
document.write('after: ' + data);

In a js regexp should i escape angle brackets? [duplicate]

I am trying to get a regex expression to accept < and > as my outside delimiters to grab all the content in between them.
so content like such
< tfdsfa >
should be grabbed.
Do I have to escape the < and > characters or something?
Regex generated by my script:
/<[^(>)]*>/g
Code from file:
data.method.highlight = function() {
var x = data.syntax,
text = data.$.span.html();
for (var i=0, len = x.length; i < len; i++) {
var rx;
if (x[i].range) {
rx = new RegExp(x[i].tag[0] + "[^(" + x[i].tag[1] + ")]*" + x[i].tag[1], "g");
console.log(rx);
}
else {
var temprx = x[i].tag[0];
for (var z = 1; z < x[i].tag.length; z++) {
temprx += "|" + x[i].tag[z];
}
rx = new RegExp(temprx, "g");
}
text = text.replace(rx,function (match) {
console.log("looping - range");
return '<span class="' + x[i].class.default + '">' + match + '</span>';
});
data.$.span.html(text);
}
};
Neither < nor > are metacharacters inside a regular expression.
This works for me:
'<foo> and <bar>'.match(/<[^>]*>/g); // ["<foo>", "<bar>"]
You could be having a problem when you try to insert the result into HTML and the browser thinks that it is not a valid HTML tag, like <blablabla>.

Javascript Addition operator Confusing & Not Working

ok im trying to learn JS but its small thing like this that is making it hard and making me want to say just forget it
for example w3schools says A+=B is the same as saying A = A + B
but when i change this code around to NOT use the A+=B operand it and code it to work as A = A + B doesnt work the same!
so that means A+=B does NOT mean the same as A = A + B then!
heres w3chools example im learning "while" loops at moment and heres is my problem below and this is THEIR code it writes "The Number is 1-19" on a new line each time as it should
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
here is MY Code Below and im basicall rewriting it from "A+=B to A = A + B" and it only writes "The Number is" ONE TIME and the number 1-19 on same line!
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "<br>The number is ";
var i = 0;
while (i < 10) {
text = text + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
You can concat the string each time in the loop:
var text = "";
var i = 0;
while (i < 10) {
var curtext = document
.getElementById("demo")
.innerHTML;
document
.getElementById("demo")
.innerHTML = curtext + "<br>The number is " + i;
i++;
}
<div id="demo"></div>
The difference between you code and W3S's is that you add the i value to text each time not the desired text so the output would be <br>The number is 123456789 to avoid that you should add <br>The number is every time:
var text = '',
text2 = ''
prefix = '<br>The number is',
i = 0;
console.clear();
while (i < 10) {
var toAppend = prefix + i
text += toAppend;
text2 = text2 + toAppend;
i++;
}
document.write(text);
document.write('<br />*****************************');
document.write(text2);

My javascript code is printing only one row. I need it to print 10 rows of 20 characters.

This is a coin flipping randomizer. I need to print out 10 rows and 20 columns. This is where I am stuck. My code seems to randomize correctly every time I click my button, it displays 20 columns but I cannot seem to get it to print a second row. It may be something simple that I am just not catching. Anything will be appreciated.
Javascript Code
function toss()
{
var heads = "x ";
var tails = "o ";
var rows = 0;
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++)
{
var val = Math.floor( Math.random() * 2 );
if(val === 1)
{
arr[i] = " x";
}
else
{
arr[i] = " y";
}
document.getElementById("results").innerHTML = arr + "<br />";
}
delete arr;
rows++
}
}
HTML:
<html>
<head>
<title>Coin Flip</title>
<script src="Toss.js" type="text/Javascript"></script>
<style>
#results
{
display: block;
}
</style>
</head>
<body>
Push Button to Flip -> <input type="button" onclick="toss()" value=" Flip ">
<span id="results"></span>
</body>
</html>
The problem is you are replacing the entire results output each time you create a row with the new row. You need to append instead of replace. So change this:
document.getElementById("results").innerHTML = arr + "<br />";
To:
document.getElementById("results").innerHTML += arr + "<br />";
You also need to move the append of the result out of the inner for loop! If you leave the append within the for loop, you will see this behavior: http://jsfiddle.net/t1s93Lqz/3/
JSFiddle: http://jsfiddle.net/t1s93Lqz/2/
You are resetting the html inside the element each iteration through the loop
document.getElementById("results").innerHTML = arr + "<br />";
And while you could concatenate innerHTML each iteration to fix this:
document.getElementById("results").innerHTML += arr + "<br />";
This will cause the whole html for that element to be re-rendered. It would be better to either build the html string first and then set the element's innerHTML property or use DOM methods like appendChild/insertAdjacentHTML.
Build string first
var html = "";
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
//moved the concatenation out of the loop
//otherwise you will get a line each as the array is set
html += arr + "<br />";
rows++
}
document.getElementById("results").innerHTML = html;
Using insertAdjacentHTML
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
Demo
var rows = 0;
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
<div id="results"></div>
Also note your delete statement won't do anything as delete works on object properties, if you console.log( delete arr ) you will see it will print false
You are only printing the last row. Replace
document.getElementById("results").innerHTML = arr + "<br />";
with
document.getElementById("results").innerHTML += arr + "<br />";

Javascript: How can I join all links (array)

I have HTML like :
<div id="divid">
1
2
3
.....................
</div>
I used script below to join, but it cannot join. Check for me.
var links = document.getElementById('divid').getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i] = links[i].href;
}
document.write('<div class="' + links.join(" ") + '">Class is added links</div>');
It means after joining I have HTML :
<div class="d#link1 d#link2 d#link3">Class is added links</div>
var as = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < as.length; i++) {
links[i] = as[i].href;
}
// work with links here
console.log('<div class="' + links.join(" ") + '">Class is added links</div>');
JSfiddle here.
Note that this causes trouble because the links are fully resolved, relative to the current domain. You might want to use another attribute to contain the classes.
Check for me.
Check it yourself.
document.getElementsByTagName returns a NodeList not an array, you'll need to
transform the nodelist into an array or just use a new array where you put in the hrefs...
Introduce a new variable:
var links = document.getElementById('divid').getElementsByTagName('a'),
hrefs = [];
for (var i = 0; i < links.length; i++) {
hrefs[i] = links[i].href;
}
document.write('<div class="' + hrefs.join(" ") + '">Class is added links</div>');
You'll need to create a separate array to hold the links.
Something like:
var links = document.getElementsByTagName('a');
var linkarr = new Array();
for (var i = 0; i < links.length; i++) {
linkarr[i] = links[i].href;
}
document.write('<div class="' + linkarr.join(" ") + '">Class is added links</div>');
Try this with jquery:
var links = $('#divid').children('a');
var linkArr = '';
for (var i = 0; i < links.length; i++) {
linksArr += links[i].attr('href') + ' ';
}
document.write('<div class="' + linksArr + '">Class is added links</div>');

Categories

Resources