keep string between two words node js express javascript - javascript

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);

Related

RegExpr and variable

I have just one question maybe stupid (like every day)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){ยด
tab.push(word[i])
}
}
console.log(tab.join(', ');
but it is dont work, i dont know how to use variable with regexpr, thanks, sorry for my english
var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null
Here is the code, but is used the test() instead of match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);
The solution using RegExp.test and Array.filter functions:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
Also, there's an additional approach using Array.indexOf function without any regex which will give the same result:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});

Cut string url in javascript

I have a string like below
var indicator = -65(www.anyweb.com)
the number -65 can be any number too. How can I take out only the web url separately in javascript?
You need to extract the string after '(' and before ')'
var str = "-65(www.anyweb.com)";
str = str.substring(str.lastIndexOf("(")+1,str.lastIndexOf(")"));
You can use this example for string operations
var data = "-65(www.anyweb.com)";
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')')); console.log("URL :: ",url);
var domain = /\((.*?)\)/.exec("-65(www.anyweb.com)")[1];
console.log(domain);
The regex above will create a group with anything that's inside parenthesis.
You can use some simple string operations:
var str = "-65(www.anyweb.com)";
var url = "N/A";
// Find indices of open and close parentheses
var open = str.indexOf("(");
var close = str.lastIndexOf(")");
// If they were found then extract the URL from the string
if (open !== -1 && close !== -1) {
url = str.substring(open + 1, close);
}
console.log(url);
If you are more inclined to use regular expressions then this should do it:
var str = "-65(www.anyweb.com)";
var regex = /\((.*?)\)/; // Capture URL inside parentheses
var result = regex.exec(str); // Execute the regex against the string
var url = "N/A";
// If the URL was matched then assign it to the variable
if (result[1] !== undefined) {
url = result[1];
}
console.log(url);
You can also simply replace the stuff that you do not want:
var str = "-65(www.anyweb.com)";
str = str.replace(/^.*\(/, ""); // Remove everything before URL
str = str.replace(/\).*$/, ""); // Remove everything after URL
console.log(str);
Example 1 :
var data = "-65(www.anyweb.com)";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 2 :
var data = "-65";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 3 :
var data = "-65(www.anyweb.com)6764872";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);

Want to get specific value from string

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

Find text between two characters and for each, do something

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.

remove all empty values from url

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('&');
}

Categories