I am trying to add and remove things in a string with using arrays. However this following script I created is not working as it doesn't remove numbers that have been submitted:
function updateCCList(id)
{
var MemberClicked = '[' + id + ']';
var ListClickedMembers = document.frmSendMail.hidSenderList.value;
if(ListClickedMembers.indexOf(MemberClicked) == -1)
{
ListClickedMembers += MemberClicked;
}
else
{
ListClickedMembers = ListClickedMembers.replace(/' + MemberClicked + '/g,'');
}
alert(ListClickedMembers);
document.frmSendMail.hidSenderList.value += ListClickedMembers;
}
Any idea what is wrong?
Many thanks,
Paul
The main problem:
ListClickedMembers = ListClickedMembers.replace(/' + MemberClicked + '/g,'');
The first RegExp there looks bad. I think you mean new RegExp('\\['+id+'\\]')
In case you care about avoiding duplicate entries:
document.frmSendMail.hidSenderList.value += ListClickedMembers;
You don't need += there, = will suffice.
Related
I receive a set of functions in text for another software program which I need to modify and then save and am trying to find the best way to do this.
I could receive a text like this:
Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)
I would like to be able to add text directly after Sum( where it is NOT immediately followed by {< Ideally my end result would like this:
Sum(TEXT_I_WANT_TO_ADD Revenue) + Sum({<CostCentre={'$(=Sum(TEXT_I_WANT_TO_ADD FIELD))'}>}COGS)
Any ideas how to achieve this in a simple way? So far my only idea was to use split and then look at the next object of the array to determine if it contains {<, however I am wondering if there is an easier way to do this.
My try (which works and but is hard to follow and not sure if it will always work):
let text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
let input_text = 'TEXT_I_WANT_TO_ADD ';
let split_text = 'Sum('
let split = text.split(split_text);
console.log(split);
let final_text = '';
for (let i in split) {
let split_modified;
// Not last item
if (i < split.length - 1) {
let next = (parseInt(i) + parseInt(1));
// Does not include {<
console.log(next, split[next]);
if (!split[next].includes('{<')) {
final_text += split_text + input_text;
}
// Does include {<
else {
final_text += split_text + split[next]
}
}
// Last item
else {
final_text += split[i]
}
}
console.log(final_text);
Any ideas how to do this is a better, easier way?
You can capture the word inside the parenthesis of Sum() and replace it :
const input_text = "TEXT_I_WANT_TO_ADD ";
const text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
const result = text.replace(/Sum\(\w+\)/g, match => `Sum(${input_text})`);
console.log(result);
sorry I just started with javascrippt and html and I am having trouble finding out what the unexpected identifier is?
here is my function
function fillSearchPlayer(data){
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i]
var item = '<tr><td>'p.firstname + ' ' + p.lastname'</td><td>'p.job'</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>'
$('#searchPlayers tbody').append('item');
}
}
maybe you guys could help me, it's saying its coming from the line that starts with "var item"
'<tr><td>'p.firstname look like you missed a plus sign over there. The other thing is .append('item'); - you probably intented to do .append(item);.
As the guys mentioned in the direct comments above you should try to use some templating engine instead of constructing the strings the way you did it.
I would recommend you to read these pieces:
Handlebars - simple and convenient template engine in JavaScript - give it a try!
Template strings in ES2016 - a cleaner way to do what you did with manual string concatenation
There are several errors. String concatenation works with +, and you're missing a semicolon.
Try:
function fillSearchPlayer(data) {
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i];
var item = '<tr><td>' + p.firstname + ' ' + p.lastname + '</td><td>' + p.job + '</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>';
$('#searchPlayers tbody').append('item');
}
}
The var item = ... item mixes variable and literal definitions without the real concatenation going on. Just put a + between each varying element to achieve your goal.
You need to enclose the concatenation operator around the p.job variable.
Your assignment should look like this...
var item = '<tr><td>'+p.firstname + ' ' + p.lastname+'</td><td>'+p.job+'</td><td><button class="cbtn" onclick=requestPlayer('+ p.identifier + ')>More</button></td></tr>'
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
In javascript, how do i split the above string("hosts") string like the following :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]"
tried this :
var hosts, newhosts;
var ip6_hosts = [];
var ip6_re = /#\[(.*?)\]/g;
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]";
while ((match=ip6_re.exec(hosts)) != null)
ip6_hosts.push(match[0]);
non_ip6_hosts=hosts.replace(ip6_re, '').replace(/:+/g, ':');
newhosts=ip6_hosts.concat(non_ip6_hosts.split(':'));
actual output :
newhosts=#[2001:db8:1/64],#[::2/24],.uk.com,hostname,#10.10.10.10/10,#11.11.11.11/11
expected output :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]
but not sure how to preserve the order. is there any way to achieve an expected output ?
You could try:
var openbracket=0;
for (i=0; i<hosts.length; i++)
{
if (hosts.substr(i,1) == '[') openbracket=openbracket+1;
if (hosts.substr(i,1) == ']') openbracket=openbracket-1;
if ((hosts.substr(i,1) == ':') && openbracket==0)
{
hosts = hosts.substr(0,i) + ',' + hosts.substr(i+1,hosts.length-i-1);
}
}
seems to work for me, though I'm not sure if there's a better method for changing the value of hosts. All it needs to do is insert the ',' at the location i. The above code adds everything to the left of the ':', a ',', and everything to the right of the ':'.
note: this assumes you don't want any ':' inside of brackets changed to a comma.
hope this helps.
Can't You just say:
host = host.replace(/:+/, ',');
whenever you want to change it?
I feel like this is too simple of an answer, comment if I'm not getting it.
The following should work:
hosts.replace(/([^:]{1})\:{1}([^:]{1})/g, '$1,$2')
Try this.
var hosts='.uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]';
hosts = hosts.replace(/:#/g, ':##');
hosts = hosts.split(':#');
var hostDetails = hosts[0].split(':');
var newHost = hostDetails.concat(hosts.splice(1, hosts.length));
console.log(newHost);
Can you try this...
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
hosts = hosts.split(':#').join(',#');
var re = /:\w/g;
var found = hosts.match(re);
hosts.replaceAt(found.index,',');
I'm programming my own autocomplete textbox control using C# and javascript on clientside. On client side i want to replace the characters in string which matching the characters the user was searching for to highlight it. For example if the user was searching for the characters 'bue' i want to replace this letters in the word 'marbuel' like so:
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
in order to give the matching part another color. This works pretty fine if i have 100-200 items in my autocomplete, but when it comes to 500 or more, it takes too mutch time.
The following code shows my method which does the logic for this:
HighlightTextPart: function (text, part) {
var currentPartIndex = 0;
var partLength = part.length;
var finalString = '';
var highlightPart = '';
var bFoundPart = false;
var bFoundPartHandled = false;
var charToAdd;
for (var i = 0; i < text.length; i++) {
var myChar = text[i];
charToAdd = null;
if (!bFoundPart) {
var myCharLower = myChar.toLowerCase();
var charToCompare = part[currentPartIndex].toLowerCase();
if (charToCompare == myCharLower) {
highlightPart += myChar;
if (currentPartIndex == partLength - 1)
bFoundPart = true;
currentPartIndex++;
}
else {
currentPartIndex = 0;
highlightPart = '';
charToAdd = myChar;
}
}
else
charToAdd = myChar;
if (bFoundPart && !bFoundPartHandled) {
finalString += '<span style="color:#81BEF7;font-weight:bold">' + highlightPart + '</span>';
bFoundPartHandled = true;
}
if (charToAdd != null)
finalString += charToAdd;
}
return finalString;
},
This method only highlight the first occurence of the matching part.
I use it as follows. Once the request is coming back from server i build an html UL list with the matching items by looping over each item and in each loop i call this method in order to highlight the matching part.
As i told for up to 100 items it woks pretty nice but it is too mutch for 500 or more.
Is there any way to make it faster? Maybe by using regex or some other technique?
I also thought about using "setTimeOut" to do it in a extra function or maybe do it only for the items, which currently are visible, because only a couple of items are visible while for the others you have to scroll.
Try limiting visible list size, so you are only showing 100 items at maximum for example. From a usability standpoint, perhaps even go down to only 20 items, so it would be even faster than that. Also consider using classes - see if it improves performance. So instead of
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
You will have this:
mar<span class="highlight">bue</span>l
String replacement in JavaScript is pretty easy with String.replace():
function linkify(s, part)
{
return s.replace(part, function(m) {
return '<span style="color:#81BEF7;font-weight:bold">' + htmlspecialchars(m) + '</span>';
});
}
function htmlspecialchars(txt)
{
return txt.replace('<', '<')
.replace('>', '>')
.replace('"', '"')
.replace('&', '&');
}
console.log(linkify('marbuel', 'bue'));
I fixed this problem by using regex instead of my method posted previous. I replace the string now with the following code:
return text.replace(new RegExp('(' + part + ')', 'gi'), "<span>$1</span>");
This is pretty fast. Much faster as the code above. 500 items in the autocomplete seems to be no problem. But can anybody explain, why this is so mutch faster as my method or doing it with string.replace without regex? I have no idea.
Thx!
I'm not sure exactly how much this question has something to do with ExtJS and how much with pure JavaScript. Anyways I have a string with comma separated value. I need to use for the GUI so I try to make it as user-friendly as I can. I made most of the things I wanted but one thing I can't accomplish yet. I want to replace all commas in the string with a proper image, which I think will fit very well on what I'm doing but for now - I try with no success.
For those familiar with ExtJS - I'm doing this for each cell in a certain column of a grid with a render function. But I think that maybe the problem must be solved with a pure JavaScript function. Here is what I have by now:
_cusomizeString: function(dates) {
if (dates != null)
{
var date = dates.replace(/,/g,"|");
var www = date.split('|');
var xxx = www.length;
for (var i = 2; i < xxx; i+=3)
{
www[i] = www[i] + '<br />';
}
var ggg = www.toString();
var hhh = ggg.replace(/,/g,'<img src =" ' + D:\dir1\dir2\dir3\dir4\dir5\img.png + ' "/>');
return hhh;
}
return dates;
}
I tried a few variations, now I don't get error but don't see an image either.
Thanks
Leron
P.S
With this change in the function:
var finalString = tempString.replace(/,/g,'<img src ="http://www.finishingtouch.co.uk/assets/images/common/calendar_icon.png"/>');
I am able to visualize this:
The main problem now is how to add the image before the first element, because now it's missing (Noticeable especially when there's only one date) and how I can make it work with local files for now? I've tried using this in my replace function:
'<img src ="file:///D:\\symapac\\src\\public\\img\\icons\\draft.png"/>'
But the console log returns this and I dont see no image:
07-06-2012<img src ="file:///D:\dir1\dir2\dir3\dir4\dir5\img.png"/>16-06-2012
Ok, I have almost final solution. Here is how it looks like:
Here is my final function:
_checkDates: function(dates) {
if (dates != null)
{
var date = dates.replace(/,/g,"|");
var arrayOfDates = date.split('|');
var stringLength = arrayOfDates.length;
for (var i = 2; i < stringLength; i+=3)
{
arrayOfDates[i] = arrayOfDates[i] + '<br />';
}
var tempString = arrayOfDates.toString();
var finalString = tempString.replace(/,/g," ,");
finalString = finalString.replace(/,/g,"<img src="+ "'" + pathToImage + "'" +"/>");
var imgSrc = "<img src="+ "'" + pathToImage + "'" +"/>";
var otuputString = imgSrc.concat(finalString);
return otuputString;
}
return dates;
}
There is that little problem that no matter now many tabs I put in var finalString = tempString.replace(/,/g," ,"); the space between the icons is always the same, no idea why. But that's the closest I get to what I've wanted.
Cheers
Leron
'<img src ="file:///D:/dir1/dir2/dir3/dir4/dir5/img.png"/>'
You have a space before your filename, also your filename isn't in quotes.