Remove Part After Last Occurrence of a Word Pattern in a String [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have this code:
var str = 'country/city/area'
var idx = str.lastIndexOf('country/city')
// idx = 0
And idx is always 0. Shouldn't idx be 12? My goal is to use it substr() in order to take the string 'area' out of the str.

var str = 'country/city/area'
var pattern = 'country/city/'
var idx = str.lastIndexOf(pattern) + pattern.length
var substring = str.substring(idx, str.length)
Explanation
1) Define the pattern you are searching for
2) Find the beginning of the pattern and add the length of the pattern => now you are at the end
3) Copy the part behind the pattern to the end of the string

if you want to get the last word, you can search for the last forward slash and get everything after it:
str.substr(str.lastIndexOf('/') + 1)
if you want to get everything after 'country/city/' but for example you don't know if this the first part of the string, you can use
str.substr(str.indexOf('country/city/') + 13);
it's not 100% clear from your question, what exactly you are trying to achieve though.

You're going to want to add the length of the string that you search for:
var str = 'country/city/area';
var checkStr = 'country/city';
var idx = str.lastIndexOf(checkStr);
var lastCharIndex = idx + checkStr.length;
// idx = 0
// idx = 12
note - it would be 12, not 13, because you didn't include the final "/" in your lastIndexOf parameter.

May be you can achieve your goal as follows;
var str = 'country/city/area',
newStr = str.replace("/area","");
console.log(newStr);

Related

Remove word before the slash with jquery [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How to remove word before slash using jquery?
/bis/admin
In my case, I want to remove "bis". any help?
You can use the JavaScript split method
var text = "/bis/admin";
var result = text.split("/");
console.log(result[result.length - 1]);
Another example
var text = "/bis/admin/dashboard";
var result = text.split("/");
console.log(result[result.length - 1]);
You could do the following using a regular expression
var el = '/bis/admin';
var newEl = el.replace(/^.*\//, "");
newEl will be 'admin'
You can just do:
let myString = '/bis/admin';
myString.split('/')[myString.split('/').length-1];
var str = "/bis/admin";
var splitStr = str.split("/");
var out = "/" + n[n.length - 1] //Out contains /admin
split string with /.
var strn = "/bis/admin";
console.log(strn.split("/")[2]);
Or you can simply use regex
var strn = "/bis/admin";
console.log(strn.replace(/^\/([^/]*)\//,""));

Regular expression for remove last n characters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a requirement to remove last n characters from string or remove 'page' from a particular string.
Eg:
var string = 'facebookpage';
Expected output string = 'facebook'
I would like to remove 'page' from the string.
Done it using substring.
var str = "facebookpage";
str = str.substring(0, str.length - 4);
Could you help me to find some better way to do it.
Regex for this:
//str - string;
//n - count of symbols, for return
function(str, n){
var re = new RegExp(".{" + n + "}","i");
return str.match(re);
};
EDIT:
For remove last n characters:
var re = new RegExp(".{" + n + "}$","i");
return str.replace(re, "");
UPDATE:
But use regex for this task, not good way; For example, AVG Runtime for 100000 iterations:
Str length solution = 63.34 ms
Regex solution = 172.2 ms
Use javascript replace function
var str = "facebookpage";
str = str.replace('page','');
You can use this regular expression :
(.*)\\w{4}
code :
var regex =(new RegExp("(.*)\\w{4}"))
val output = regex .exec("facebookpage")
// output is : ["facebookpage", "facebook"]
// output[1] is the Expected output which you want.
Hope this helps.

Extract a part of a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I need to extract a part of a string. My goal is to extract from this string:
217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email
the content between utmcsr= and |
So the output would be : "search_email_alerts".
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var newStr1 = str.split("utmcsr=");
var newStr2 = newStr1[1].split("|");
var extractedStr = newStr2[0];
The variable extractedStr will be "search_email_alerts".
Use regular expression like following:
var test = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var result = test.match("/utmcsr=([^|]*)\|/");
alert(result[1]); // result[1] is your desired string
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
match = str.match(/utmcsr=(.*?)\|/);
output = match[1];
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email"
var result = str.substring(str.indexOf("utmcsr=") + 7,str.indexOf("|"))
Result contains the desired text.
You can do that in two ways
substring
match
Here's how you can do it with regex:
var str= "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var res = str.match(/^.*utmcsr=(.*)\|.*\|.*$/);
res[1]
Here you go -
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var startIndex = str.indexOf("utmcsr=") + "utmcsr=".length;
var numOfCharsToExtract = str.indexOf("|") - startIndex;
var result = str.substring(startIndex, numOfCharsToExtract);

Regex : split string based on first occurrence, with occurance [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am terrible at regex. Please have pity and give me a hand.
I am trying to split a string by the first occurrence of And (case sensitive), into an array with a length of 2. I have no idea were to begin, so can someone help me?
var strArr = "Thing And other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing","And other thing"]);
var strArr = "Thing and other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing and other thing", ""]);
var strArr = "One Thing And other thing And yet another thing".split(/magic regex/);
expect(strArr).to.deep.equal(["One Thing","And other thing And yet another thing"]);
var strArr = "yep, just one thing".split(/magic regex/);
expect(strArr).to.deep.equal(["yep, just one thing", ""]);
UPDATE this is working exactly the way I need it to, but its still ugly:
parser = function(str) {
var spl;
spl = str.split(/\s(?=And )/);
if (spl.length > 1) {
spl = [spl.shift(), spl.join(" ")];
} else {
spl = [str, ''];
}
return spl;
};
There is no need for a regular expression for that. Just get the first index of "And" in the string:
var i = str.indexOf("And");
var strArr;
if (i == -1) {
strArr = [ str ];
} else {
strArr = [ str.substr(0, i), str.substr(i) ];
}
While Guffa's method works, if you end up needing to do this the regex way, the following will work (via a positive lookahead):
var str = "Thing And other thing";
var spl = str.split(/\s(?=And\s)/);
if (spl.length > 1)
spl = [spl.shift(), spl.join(" ")];
To test:
alert(JSON.stringify(spl));
jsFiddle
Updated to ensure it splits on [space]And[space]
I suggest doing a simple split then checking if the array has one or two
strArr.split("And", 2).length;

How to do something on every first letter? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
var s='Color sentence';
My task is to do something on every first consonant . For example in this sencente "Color sentence" i need to color letters C,L,R,S,N,E,C etc.
But i need code to count every first letter .Help(I'm newbie.) ?
Assuming you're going to insert that string as HTML ?
var s = 'Color sentence';
var a = s.split(' ');
for (var i=0; i<a.length; i++) {
a[i] = '<span style="color:red">' + a[i].charAt(0) + '</span>' + a[i].slice(1);
}
var s = a.join(' ');
FIDDLE
for every other letter in the string, you'd do:
var s = 'Color sentence';
var a = s.split('');
for (var i=0; i<a.length; i++) {
if (i%2)
a[i] = '<span style="color:red">' + a[i].charAt(0) + '</span>' + a[i].slice(1);
}
var s = a.join('');
FIDDLE
You can simply call
s[0] //to get the first character in the string.
var x = "Hello";
var y = x[0];
alert(y);
Output: "H"
To do somewthing with every other character, you can use a regular expression to put an HTML element around them so that you can style them:
s = s.replace(/(^|.)(.)/g, '$1<span>$2</span>');
Demo: http://jsfiddle.net/Guffa/vLEhh/
Regular expression explanation:
(^|.) - catches the beginning of the string or one character into $1
(.) - catches one character into $2
So, the expression matches either the start of the string or one character, followed by another character. The first match in the string will be the first character, from then on it will match two characters at a time.

Categories

Resources