I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.
Related
I have the following string:
var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';
how can i get with the least code the someExtraStuff.fileExt section?
should i do indexOf {{appName}} and then until the next "/> ?
You could search for the pattern {{appName}} and take all characters who are not quotes. Then take the second element of the match.
var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]
console.log(substring);
You can do this with three methods
// 1 option
For single match
var regex = /\{\{appName\}\}([^"]+)/;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
console.log(myString.match(regex)[1]);
// 2 option
For multiple matches
var regex = /\{\{appName\}\}([^"]+)/g;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
var temp;
var resultArray = [];
while ((temp = regex.exec(myString)) != null) {
resultArray.push(temp[1]);
}
console.log(resultArray);
// 3 option For indexOf
var firstIndex= myString.indexOf("{{appName}}");
var lastIndex =firstIndex+ myString.substring(firstIndex).indexOf('"/>')
var finalString = myString.substring(firstIndex,lastIndex).replace("{{appName}}","");
console.log(finalString);
I have a string like:
var str = put returns between paragraphs abc_start indent code by 4 spaces abc_end quote by placing > at start of line abc_start to make links abc_end.
I'm displaying this string in my browser using:
res.send('/page/+result);
I want to filter out result such that only the content which starts at abc_start and end at abc_end remains. How do I do that in node.js?
For eg: output:
abc_start indent code by 4 spaces abc_end abc_start to make links abc_end
I tried using : str.split('abc_start').pop().split('abc_end').shift();
But I'm not gettting desired output.Please help.
<script>
function myFunction() {
var str = "abc_start indent code by 4 spaces abc_end";
var n = str.indexOf("abc_start ");
var m = str.indexOf("abc_end");
var res = str.slice(n+9, m-1);//Since you already know the length of the string "abc_start" that you want out of the way
document.getElementById("demo").innerHTML = res;
}
</script>
Below is code snippet to solve this scenario:
var str = 'xxxadasyyydsdsxxxadadyyy';
var start = 'xxx';
var end = 'yyy'
var res = [];
find();
function find() {
var initialIndex = str.indexOf(start);
var lastIndex = str.indexOf(end);
if(initialIndex > -1 && lastIndex > -1 && initialIndex < lastIndex) {
res.push(str.substring(initialIndex, lastIndex + start.length));
str = str.substring(lastIndex + start.length);
find();
} else {
return;
}
}
console.log(res);
I have data two sets of data as follows:
"One.Two.Three.Four"
"One.Two.Three.1.Four"
The first three parts are fixed and the remaining can extend to as many as possible.
I am trying to build an object where I want to split and combine whatever is present after three into an object.
var split = samplestr.split('.');
var finalarray = [];
if(split.length>4)
{
finalarray[0] = split[0];
finalarray[1] = split[1];
finalarray[2] = split[2];
finalarray[3] = split[3]+"."split[4];
}
I need to generalise this such that even if the string is of the form
"One.Two.Three.1.2.3.Four"
finalarray[3] = 1.2.3.Four;
Any hints on generalising this?
With Array#shift and Array#join.
var split = samplestr.split('.');
var finalarray = [];
if(split.length > 4) {
finalarray[0] = split.shift();
finalarray[1] = split.shift();
finalarray[2] = split.shift();
finalarray[3] = split.join(".");
}
simply replace
finalarray[3] = split[3]+"."split[4];
with
finalarray[3] = split.slice(3).join(".");
Split the string, slice the first part and append the join'ed second part:
console.info=function(x){document.write('<pre>'+JSON.stringify(x,0,3)+'</pre>')}
//--
var str = "One.Two.Three.Four.More.Stuff";
var s = str.split('.');
var result = s.slice(0, 3).concat(s.slice(3).join('.'));
console.info(result);
I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example
I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}