Regular expression for remove last n characters [closed] - javascript

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.

Related

Regex to check for a repeated Pattern in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So I have a text with a pattern where there are two constant letters (start, end) and in between them there can be any letter. For example if start is X and end is Y. Then I could have something like this:
ABCDXaYXpYXpYXlYXeYEFGHOASDASDADASD
Which is the word apple where each letter is sorrounded by X and Y
What would be the regex where I can match only the string XaYXpYXpYXlYXe? Thank you for your help.
Here's the answer for the edited version. A bit of ugly trickery, but oh well.
var str = "ABCDXaYXpYXpYXlYXeYEFGHOASDASDADASD";
var regex = /(?<=[XY])(.*)(?=[XY])/;
var result = str.match(regex);
regex = /[XY]/g;
result = result[0].replace(regex, ""); // "apple"
You could either match anything that isn't X or Y (although it'll break it up into substrings):
var str = XaYXpYXpYXlYXeY;
var regex = /[^XY]/g; //case sensitivity optional
var result = str.match(regex) // ["a", "p", "p", "l", "e"]
or you could replace all of the X and Y with blank spaces.
var str = XaYXpYXpYXlYXeY;
var regex = /[XY]/g; //case sensitivity still optional
var result = str.replace(regex, ""); // "apple"

JavaScript - check string for substring and capitalize substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would I test a string to see if it contains a specific substring and then capitalize that substring?
var string = " A Fine and Rare George Iii Neoclassical Ormolu Urn Clock"
And find and capitalize the Roman numeral to III.
Another example:
var string2 = "Platinum Pf00673"
Find and capitalize letters in strings that contain numbers, so the above becomes PF00673
You can make use of the callback to String#replace.
var string2 = "Platinum Pf00673";
var result = string2.replace(/\w*[0-9]\w*/g, match=>match.toUpperCase());
console.log(result);
Use regex to match and replace.
var string2 = "Platinum Pf00673"
var reg = new RegExp("[A-Z]+[0-9]+[A-Z0-9]+", "gi");
var matches = string2.matchAll(reg);
for(var match of matches)
{
var parts = string2.split("");
parts.splice(match.index, match[0].length, ...match[0].toUpperCase().split(""));
string2 = parts.join("");
}
console.log(string2);
A simple solution could be to create a helper function like so
const capitlizeSubStr = (string, substring) => {
const regex = new RegExp(substring, 'gi')
const newString = string.replace(regex, substring.toUpperCase())
return newString
}
Answering for the Roman Numeral question.
var string1 = "A Fine and Rare George Iii Neoclassical Ormolu Urn Clock";
var result = string1.replace(/M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})/ig, match=>match.toUpperCase());
console.log(result);
It's an extension of hev1's answer.
capitalize romans:
'world war Iii'.replace(/\w+/g, word => word.match(/^[MCDXVI]+$/i) ? word.toUpperCase() : word)
// "world war III"
capitalize words with digits
'Platinum Pf00673'.replace(/\w+/g, word => word.match(/\d/) ? word.toUpperCase() : word)
// "Platinum PF00673"

Ho do I split these 2 string using Regex? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Following are 2 strings:
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)"
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
How do I split them to these using JS and Regex?
['callback', '/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js', '541', '21']
['', '/Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js', '269', '22']
try regexp named groups
https://github.com/tc39/proposal-regexp-named-groups
it adds result readability for such strange regexes ;)
const strings = [
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)",
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
];
const regex = /^\s*?at\s?(?<source>.*?)\s\(?(?<path>.*?):(?<row>\d*):(?<column>\d*)/;
strings.forEach(string => {
const result = string.match(regex);
resultElement.innerHTML +=
'\n' + JSON.stringify({string, "result.groups": result.groups}, null, 4)
})
<pre id="resultElement"/>
You can use regex for such purpose, i.e:
const regex = /at( (?:[a-z]+)?)\(?(.+)\:(\d+)\:(\d+)\)?/;
//const str = " at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)";
const str = " at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22";
const found = str.match(regex);
found.splice(0, 1)
console.log(found)
It works for both strings!
I've wrote simple parse function for you:
function parse(string) {
const functionName = string.match(/at .* /);
return [
...(functionName && [functionName[0].slice(2).trim()] || ['']),
...string.match(/\/.*/)[0].split(':')
];
}
First of all I try to extract function name. If it exists I remove 'at' word and use trim function to remove unnecessary spaces. Then I look for substring beginning with slash '/' and match every character after it. Last step is to split returned string.
I believe it matches your requirements.
I've also prepared demo in stackblitz: https://stackblitz.com/edit/js-ol22yf

Remove Part After Last Occurrence of a Word Pattern in a String [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 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);

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

Categories

Resources