I've a HTML string that looks as follows
var hoverData = "<table id='hvr-revision_history'><tr><td>{date_value}2013-07-29T11:52:38Z{date_value}</td><td>Error1</td></tr><tr><td>{date_value}2013-07-30T11:52:38Z{date_value}</td><td>Error2</td></tr><tr><td>{date_value}2013-07-31T11:52:38Z{date_value}</td><td>Error3</td></tr></table>";
The final output needed is
"<table id='hvr-revision_history'><tr><td>07/29/2013 11:52:38 AM</td><td>Error1</td></tr><tr><td>07/30/2013 11:52:38 AM</td><td>Error2</td></tr><tr><td>07/31/2013 11:52:38 AM</td><td>Error3</td></tr></table>"
My approach is
var sindex = 0;
while(true){
var sindex = hoverData.indexOf("{date_value}"); //startindex
if(sindex <0)
break;
var eindex = hoverData.indexOf("{date_value}",sindex+1); //endindex
var date = hoverData.substring(sindex+12,eindex); //string between {date_value} tags, so 2013-07-29T11:52:38Z
//logic to parse the date
var hoverData = hoverData.replace(date,parsedDate);
}
var hoverData = hoverData.replace("{date_value}","");
Is there a better approach?
My code will fail if I've 2 or more dates that are exactly the same.
You can match the individual date chunks as a regular expression, with a function (instead of a string) as the replacement. That function can call your parse function, which I've stubbed out here since you didn't include it.
var hoverData = "<table id='hvr-revision_history'><tr>" +
"<td>{date_value}2013-07-29T11:52:38Z{date_value}</td>" +
"<td>Error1</td></tr>" +
"<tr><td>{date_value}2013-07-30T11:52:38Z{date_value}</td>" +
"<td>Error2</td></tr>" +
"<tr><td>{date_value}2013-07-31T11:52:38Z{date_value}</td>" +
"<td>Error3</td></tr></table>";
// your "logic to parse the date" would go here
function parseDate(str) {
return "( parsed " + str + " )";
}
// look for our delimiters with *only* the legal timestamp
// characters between them
hoverData = hoverData.replace(/\{date_value\}([A-Z0-9\-\:]+)\{date_value\}/g,
// match gets the fully-matched string, plus any captured patterns
// (the parenthesized chunk) as separate parameters. `datepart` will
// contain the matched timestamp string only
function (match, datepart) {
return parseDate(datepart);
}
);
hoverData = hoverData.replace("{date_value}","");
See it in action here: http://codepen.io/paulroub/pen/CGqlh
Related
Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)
I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>
In the below code Im not getting the right result. How can I can do pattern match in javascript?
function getPathValue(url, input) {
console.log("this is path key :"+input);
url = url.replace(/%7C/g, '|');
var inputarr = input.split("|");
if (inputarr.length > 1)
input = '\\b' + inputarr[0] + '\n|' + inputarr[1] + '\\b';
else
input = '\\b' + input + '\\b';
var field = url.search(input);
var slash1 = url.indexOf("/", field);
var slash2 = url.indexOf("/", slash1 + 1);
if (slash2 == -1)
slash2 = url.indexOf("?");
if (slash2 == -1)
slash2 = url.length;
console.log("this is path param value :"+url.substring(slash1 + 1, slash2));
return url.substring(slash1 + 1, slash2);
}
getPathValue("http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1","mountainwithpassid|passid")
Im getting the below output
If I pass mountainwithpassid|accesscode as input Im getting output as
100. Same way if I pass
key :mountainwithpassid|passid value :100 // Expected output 1
If your intention is to simply retrieve the value in the path that follows the input (contained within '/') then you can achieve this with a simpler regular expression. First you will need a method to escape your input string since it contains a pipe character '|' which is translated as OR in regex.
You can use this (taken from https://stackoverflow.com/a/3561711):
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
Then your getPathValue function can look something like:
function getPathValue(url, input) {
var pathValue = null;
var escapedInput = RegExp.escape(input);
// The RegExp below extracts the value that follows the input and
// is contained within '/' characters (the last '/' is optional)
var pathValueRegExp = new RegExp(".*" + escapedInput + "/([^/]+)/?.*", 'g');
if (pathValueRegExp.test(url)) {
pathValue = url.replace(pathValueRegExp, '$1');
}
return pathValue;
}
You will also need to think about how you handle errors - in the example a null value is returned if no match is found.
I'm trying to understand the question. Given a URL of:
"http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1"
and an argument of:
"mountainwithpassid|passid"
you expect a return value of:
"1"
An argument of
"mountainwithpassid|accesscode"
should return:
"100"
Is that correct? If so (and I'm not certain it is) then the following may suit:
function getPathValue(url, s) {
var x = url.indexOf(s);
if (x != -1) {
return url.substr(x).split('/')[1];
}
}
var url = "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1";
var x = "mountainwithpassid|passid";
var y = "mountainwithpassid|accesscode";
console.log(getPathValue(url, x)); // 1
console.log(getPathValue(url, y)); // 100
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
I've never done this before and am not sure why it's outputting the infamous � encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
You could ammend your code to make a string (without the '\u') from your hex number, and call
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode() with that value.
A useful snippet for replacing all unicode-encoded special characters in a text is:
var rawText = unicodeEncodedText.replace(
/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCode and parseInt
If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i) would be a lot easier...