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
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 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.
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/
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
The id of my textarea is string and of this format
id='fisher[27].man'
I would like to clone the textarea and increment the number and get the id as fisher[28].man and prepend this to the existing textarea.
Is there a way to get this done easily with jquery?
var existingId = $("#at textarea:last").attr('id');
var newCloned = lastTextArea.clone();
var newId = newCloned.attr('id');
//add the index number after spliting
//prepend the new one to
newCloned.prepend("<tr><td>" + newCloned + "</td></tr>");
There has to be easier way to clone, get index number, split and prepend.
I'm have also tried to do this with regEx
var existingIdNumber = parseInt(/fisher[(\d+)]/.exec(s)[1], 10);
Can anybody help me with this?
Correct regex would be this
/fisher\[\d+\].man/
Here is a way through through which you would extract the the id.
id = text.replace(/fisher\[(\d+)\].man+/g,"$1");
//Now do whatever you want with the id
Similarly, Same replacement technique can be used to get an incremented id as:
existingId = 'fisher[27].man';
newId = existingId .replace(/(\d+)+/g, function(match, number) {
return parseInt(number)+1;
});
console.log(newId);
Demo with both usage
jsFiddle Demo
No need for all the extra code. Change this line:
var newId = newCloned.attr('id');
To:
var newId = newCloned.attr('id').replace( /(\d+)/, function(){return arguments[1]*1+1} );
Another easy solution from this question's accepted answer:
'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"
Very clean and readable.
If your Id has this format
id='fisher[27].man'
You can do something like this
var startIndex = newId.indexOf('[');
var endIndex = newId.indexOf(']');
var number = parseInt(newId.substr(startIndex + 1, endIndex - startIndex - 1));
var incrementedId = number + 1; // 28
where
var newId = newCloned.attr('id');
I am amazed that there is not any good implementation for this simple thing. All of the examples forget the case of having zeroes before the number. The code below should take care of that.
// 'item001' => 'item002'
function increment_alphanumeric_str(str){
var numeric = str.match(/\d+$/)[0];
var prefix = str.split(numeric)[0];
function increment_string_num(str){
var inc = String(parseInt(str)+1);
return str.slice(0, str.length-inc.length)+inc;
}
return prefix+increment_string_num(numeric);
}
Example:
> increment_alphanumeric_str('test09')
'test10'
Only drawback is that this will break if we have something like 'test99'.
You can do this pretty easily with a regex replacement:
var id = "fisher[27].man";
id = id.replace(/\[(\d+)\]/, function(match, number) {
return '[' + (parseInt(number, 10) + 1) + ']';
});
// id is now "fisher[28].man"