Renaming/Modifying using current name in javascript - javascript

I am new to javascript, i tried to modify a text shown below with substring command.
eg. "ABCD_X_DD_text" into "ABCD-X(DD)_text" this
i used this
var str = "ABCD_X_DD_cover";
var res = str.substring(0,4)+"-"+str.substring(5,6)+"("+str.substring(7,9)+")"+str.substring(9,15);
// print to console
console.log(res);
i got what i want. But problem is X and DD are numerical (digit) value. and they are changeable. here my code just stop working.
it can be ..... "ABCD_XXX_DDDD_text" or "ABCD_X_DDD_text".
could you suggest some code, which works well in this situation.

You can use a split of the words.
var strArray = [
"ABCD_X_DD_cover",
"ABCD_XX_DD_cover",
"ABCD_XXX_DD_cover"
];
for(var i = 0; i < strArray.length; i++){
var split = strArray[i].split("_");
var str = split[0] + "-" + split[1] + "(" + split[2] + ") " + split[3];
console.log(str);
}
I used a for cycle using an array of strings, but you can do it with a variable too.

Related

Concatenate string in typescript/javascript

EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.
I am trying to concatenate a string such that I get the following output:
"OR("1admin", "2admin")"
But the output I keep on getting is
"OR(\"1admin\", \"2admin\")"
Sample code
var str = "OR("
for (let i = 1; i < 3; i++) {
str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)
I have tried using regex and string split.
eg.
.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "
.split('\\').join('').trim() This also didn' work.
What am I doing wrong?
As mentioned, you already got the correct result in your original snippet.
If the character escape syntax seems curious to you, I'd recommend something like the following using template strings.
You can write the " in template strings unescaped and use interpolation to print your variables.
Edit: Seems like you want JSON formatting. You can use JSON.stringify for that. JSON formatted strings will contain escape characters that show up in console.log output.
const f = (n, s) => {
const a = new Array(n)
.fill()
.map((_, i) => `"${i + 1}${s}"`);
return `OR(${a.join(', ')})`;
}
console.log(`output: ${f(2, "admin")}`)
console.log(`json-formatted: ${JSON.stringify(f(2, "admin"))}`)
This seems to do the job:
const NUM_ADMINS = 2;
const CONCAT_STRING =
`OR(${
Array(NUM_ADMINS)
.fill()
.map((_, idx) => `"${idx + 1}admin"`)
.join(", ")})`;
It creates a new array with the needed number of admins, then maps it to strings in th form "admin", joins with a comma and a space. And then it it is all wrapped in a "OR()" string.
var str = '"OR("'
var adm = 'admin"'
var end = ')"'
for (let i = 1; i < 3; i++) {
str += i + adm + ', '
}
str = str.trim().substring(0, str.length - 2)
str += end
console.log(str);
try running this snippet. if the implementation is fyn for you. Result is what you expected.

Javascript-split() not working when there are repeated chars in a string

Not sure how valid is this approach, but I'm unable to split the string into 2 when there are repeated characters.
var match = 's';
var str = "message";
var res = str.split(match, 2);
For instance i tried to use split() on the string "message", it results into:
me,""
So i did this:
res = str.split(match, 3);
so now it resulted into:
me,,age
but as you can see im still missing the second 's' in the "message" string. what im trying to get is I'm passing a matched character (in above case var match which is dynamically generated) to the split() and splitting into 2. I was hoping to get something this:
res = me,,sage
is that possible using split() or is there a better method to achieve this?
P.S: in fiddle i've given another string eg: (string = "shadow") which works fine.
Fails only when there are repeated letters in the string!
fiddle: https://jsfiddle.net/ukeeq656/
EDIT::::::::::::
Thanks everyone for helping me out on this...and so sorry for last min update on the input, i just realized that var match; could be a word too, as in var match = 'force'; and not just var match ='s'; where the string is "forceProduct", so when my match is more than just a letter, this approach works: str.split(match, 2);, but str.indexOf(match); doesnt obviously... could there be an approach to split: "","Product". My extreme apologies for not mentioning this earlier.any help on this would be appreciated!!
eg fiddle:
https://jsfiddle.net/ukeeq656/3/
I don't think split() is the correct way to do this.
Please see below:
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res =[];
res[0] = str.substring(0, index);
res[1] = " ";
res[2] = str.substring(index + 1);
console.log(res);
I'm not sure what your end goal is but I think this gets you what you want.
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res = str.substring(0, index) + ',' + str.substring(index + 1);
alert(res); // me,sage
You could write a function to do this;
function newSplit(str, match) {
var num = str.indexOf(match);
var res = [];
res.push(str.substring(0, num));
//res.push(str.substring(num + 1, str.length)); // this line has been modified
res.push(str.substring(num + match.length, str.length));
return res;
}
var match = 'force';
var str = 'forceProduct';
console.log(newSplit(str, match));
This is what you want?

javascript replace string/html from array

I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/

Cannot read properly "split"

I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.

replace HTML text with incrementing numbers in javascript

I have a bunch of text with no HTML, and I'm trying to find all replace all instances of String with <span id="x">String</span>
The catch is I'm trying to increment x every time to get a bunch of uniquely identifiable spans rather then identical ones.
I have no problem getting all instances of String, but for the life of me I can't get the increment to work. All help I can find seems to be directed towards doing the opposite of this.
Any ideas what I can do or where else to turn for help?
EDIT:
This is targeting a div with ID 'result' that contains only text.
var target = "String";
var X = //the number I was trying to increment
var re = new RegExp(" " + target + " ","g");
document.getElementById('result').innerHTML = document.getElementById('result').innerHTML.replace(re, '<span id="' + X + '">' + target + '</span>');
I'm guessing you are using a regex, which is fine, but you can specify a function as the second parameter to replace and do your logic there.
The MDN documentation for doing this is here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
You could use something like this:
http://jsfiddle.net/gjrCN/2/
function replacer(orig, target) {
var x = 0;
var re = new RegExp(target, "g");
var ret = orig.replace(re, function (match) {
return "<span id='" + (++x) + "'>" + match + "</span>";
});
return ret;
}
var example = "String Stringasdf String2344 String";
var replaced = replacer(example, "String");
console.log(replaced);
You can change ++x to x++ if you want the counting to start at 0 instead of 1.
With reference to these docs.
You can pass a function to the String.replace method would allow you to increment a counter with each call and use that to set your ID:
var forReplacements = "I do like a String that's a nice long String with Strings in it";
var incrementer = (function() {
var counter = -1;
var fn = function(match) {
counter++;
return "<span id='"+counter+"'>"+match+"</span>";
};
fn.reset = function() {
counter = -1;
}
return fn;
}());
var newString = forReplacements.replace(/String/g, incrementer )
See this fiddle to see it in action

Categories