Replacing array elements using regex and replace() in javascript - javascript

I'm bit new to JavaScript, I'm trying to replacing the array element using regex that matches the string, here is a code which I tried
<button onclick="myFunction()">ClickHere</button>
<p id="demo"></p>
<script>
function myFunction() {
var abc = ["deno", "eno","pqr","lenovo"];
var i,text;
for(i = 0; i < abc.length; i++) {
text += abc[i].replace(/no/i, "po");
document.getElementById("demo").innerHTML = text;
}
}
</script>
I want to replace array element with "po" wherever it encounters "no" in the array element string.
This is what I expect:
abc["depo","epo","pqr","lepovo"]

You can do this for every element:
for(var i=0; i < abc.length; i++) {
abc[i] = abc[i].replace('no', 'po');
}
or using one line
abc = abc.map(function(x){return x.replace('no', 'po');});
or using one line with "arrow functions":
abc = abc.map(x => x.replace('no', 'po'));
After you changed the array, you can convert it to a string using:
var text = 'abc[';
for ( var i = 0 ; i < abc.length ; i++ ) {
text+='\"'+abc[i]+'\"';
if ( i != abc.length - 1) {
text+=',';
}
}
text += ']';
Test:
function myFunction() {
var abc = ["deno", "eno","pqr","lenovo"];
abc = abc.map(x => x.replace('no', 'po')); // see other 2 alternatives above
var text = 'abc[';
for ( var i = 0 ; i < abc.length ; i++ ) {
text+='\"'+abc[i]+'\"';
if ( i != abc.length - 1) {
text+=',';
}
}
text += ']';
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">ClickHere</button>
<p id="demo"></p>

var i, text;
for(i = 0; i < abc.length, i++) {
text += abc[i].replace("no", "po");
}
console.log(text);

There are three changes required in your code:
Initialiize text with empty string.Because it is undefined by default.
Change abc[i].length to abc.length.
Replace comma with a semicolon after abc[i].length in for loop.
var abc = ["deno", "eno","pqr","lenovo"];
var i;
var text = "";
for(i = 0; i < abc.length; i++) {
text += abc[i].replace("no", "po");
}

Related

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

replace odd and even occurence with html javascript

I am trying to replace ` ticks with html code in a string.
var str = "this `code` and `here`"
my expected output
"this code and here"
What i am trying to do is below
.
get the positions with ticks in a string
replace those ticks with span html based on odd and even occurence.
not sure, i couldnt get expected and my browser gets hang. and
when i debug it. i see there is no index for string to replace.
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
You can use String.prototype.replace() with RegExp
/(`\w+`)/g
String.prototype.slice() with parameters 1, -1 to slice string within backtick
`
characters
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
.code {
background: turquoise;
}
scope of var i is wider then you think, so pos.push(i) will have them all same at the end
replaceAt appends incorrect ending
replaceAt shifts rest of the string invalidating positions you found
I believe you wanted something along these lines:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)
Use the JavaScript replace method.
var str = "this `code` and `here`";
var newStr = str.replace("`", "");

Save and return randomly generated strings in local storage

Okay so basically what I'm trying to do is to display all the randomly generated strings on the page, after being saved in sessionStorage. So far, my createRandom function works fine on its own, but when I added the returnRandom function both stopped working. I appreciate any suggestions.
Here is the javascript:
function createRandom()
{
var text = "";
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i = 0; i < 5; i++ )
text += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
document.getElementById("randomstring").innerHTML= text;
sessionStorage.setItem(text, text);
returnRandom();
}
document.getElementById("button").addEventListener("click", createRandom, false);
// //returns session storage values
function returnRandom() {
var key = "";
var i = 0;
for (var i = 0, i <= sessionStorage.length - 1, i++) {
key = sessionStorage.key(i);
var item = sessionStorage.getItem(key);
document.getElementById("randomreturn").innerHTML += item;
}
}
And here is the html:
<h2 id="randomstring">Random</h2>
<div id="button">
<p class="buttontext">Click Me</p>
</div>
<h3 id="randomreturn"></h3>
Your for loop expression should have semicolons, not commas
for (var i = 0; i <= sessionStorage.length - 1; i++)

Javascript - How to replace white spaces which are not in HTML tags?

The following codes doesn't work and the result is broken because there are white spaces in a HTML tag.
HTML:
<div>Lorem ipsum <a id="demo" href="demo" rel="demo">dolor sit amet</a>, consectetur adipiscing elit.</div>
Javascript:
var div = document.getElementsByTagName('div')[0];
div.innerHTML = div.innerHTML.replace(/\s/g, '<span class="space"> </span>');
How to replace replace white spaces which are not in HTML tags?
It would be a better idea to actually use the DOM functions rather than some unreliable string manipulation using a regexp. splitText is a function of text nodes that allows you to split text nodes. It comes in handy here as it allows you to split at spaces and insert a <span> element between them. Here is a demo: http://jsfiddle.net/m5Qe8/2/.
var div = document.querySelector("div");
// generates a space span element
function space() {
var elem = document.createElement("span");
elem.className = "space";
elem.textContent = " ";
return elem;
}
// this function iterates over all nodes, replacing spaces
// with space span elements
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
// it's an element node, so call recursively
// (e.g. the <a> element)
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2; // childNodes is a live array-like object
// so it's necessary to advance the loop
// cursor as well
}
}
}
}
You can deal with the text content of the container, and ignore the markup.
var div = document.getElementsByTagName('div')[0];
if(div.textContent){
div.textContent=div.textContent.replace(/(\s+)/g,'<span class="space"> </span>';
}
else if(div.innerText){
div.innerText=div.innerText.replace(/(\s+)/g,'<span class="space"> </span>';
}
First split the string at every occurrence of > or <. Then fit together all parts to a string again by replacing spaces only at the even parts:
var div = document.getElementsByTagName('div')[0];
var parts = div.innerHTML.split(/[<>]/g);
var newHtml = '';
for (var i = 0; i < parts.length; i++) {
newHtml += (i % 2 == 0 ? parts[i].replace(/\s/g, '<span class="space"> </span>') : '<' + parts[i] + '>');
}
div.innerHTML = newHtml;
Also see this example.
=== UPDATE ===
Ok, the result of th IE split can be different then the result of split of all other browsers. With following workaround it should work:
var div = document.getElementsByTagName('div')[0];
var sHtml = ' ' + div.innerHTML;
var sHtml = sHtml.replace(/\>\</g, '> <');
var parts = sHtml.split(/[<>]/g);
var newHtml = '';
for (var i = 0; i < parts.length; i++) {
if (i == 0) {
parts[i] = parts[i].substr(1);
}
newHtml += (
i % 2 == 0 ?
parts[i].replace(/\s/g, '<span class="space"> </span>') :
'<' + parts[i] + '>'
);
}
div.innerHTML = newHtml;
Also see this updated example.
=== UPDATE ===
Ok, I have completly changed my script. It's tested with IE8 and current firefox.
function parseNodes(oElement) {
for (var i = oElement.childNodes.length - 1; i >= 0; i--) {
var oCurrent = oElement.childNodes[i];
if (oCurrent.nodeType != 3) {
parseNodes(oElement.childNodes[i]);
} else {
var sText = (typeof oCurrent.nodeValue != 'undefined' ? oCurrent.nodeValue : oCurrent.textContent);
var aParts = sText.split(/\s+/g);
for (var j = 0; j < aParts.length; j++) {
var oNew = document.createTextNode(aParts[j]);
oElement.insertBefore(oNew, oCurrent);
if (j < aParts.length - 1) {
var oSpan = document.createElement('span');
oSpan.className = 'space';
oElement.insertBefore(oSpan, oCurrent);
var oNew = document.createTextNode(' ');
oSpan.appendChild(oNew);
}
}
oElement.removeChild(oCurrent);
}
}
}
var div = document.getElementsByTagName('div')[0];
parseNodes(div);
Also see the new example.

adding unique class for new div

I want add a unique class for each new div after input, how is it in my code?
Add class for this: <div class="thing"></div>
DEMO: http://jsfiddle.net/wAwyR/2/ => please in here(field) typing a number for adding new input.
function unique() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$('input').live("keyup", function () {
$('.lee').empty();
var $val = $(this).val();
for (var i = 0; i < $val; i++) {
$('.lee').append('<input type="text" name="hi" class="">div class="thing"></div>');
$('input[hi]').next('div').attr('class', unique())
}
});
var increment = 0;
function unique() {
return "u" + increment++;
}
can't that work?

Categories