I got a string
For example:
This is for trails and I want to learn Js and Coding and Development
The above mentioned line as a string
function trail(sen){
var cat = "and"
var fin = sen.indexOf(cat);
if(fin > 0){
var last = sen.substring(0, fin)
}
else{
var last = sen;
}
return last;
}
console.log(
trail("This is for trails and I want to learn Js and Coding and Development ")
);
I am trying to find the index of the second "and" in a string rather than the first one.
and get the string part from index 0 to that second "and"
Could you please provide the better approach ?
You can use split together with join to achieve this, like so:
const myStr = 'This is for trails and I want to learn Js and Coding and Development'
const subStr = 'and'
const splitted = getSplitted(myStr, subStr, 2) // Splits before the "N th" ocurrence of subStr
console.log(splitted)
function getSplitted(str, subStr, idx) {
return str.split(subStr, idx).join(subStr);
}
You can first find the second occurrence and then remove it via simple slice.
This method also supports regular expressions as pattern.
/**
* Find the n-th occurrence of given pattern in a string.
* #param { string } str The string to be examined.
* #param { string | RegExp } pattern The pattern to be matched.
* #param { number } n Starting index.
* #return { [number, string | RegExpExecArray] } The index & the match result. `[-1, null]` if pattern occurs less than n times.
*/
function findNth(str, pattern, n = 1) {
// The total processed index & and the last match
let index = 0, result;
for(; n--; ) {
// Index of the next match relative to the end of the last one
let offset = -1;
if(pattern instanceof RegExp) {
const match = pattern.exec(str);
if(match !== null) {
offset = match.index;
result = match[0];
}
}
else { // string case
offset = str.indexOf(pattern);
result = pattern;
}
// If none is matched
if(offset === -1)
return [-1, null];
// Seek over the match result
offset += result.length;
str = str.slice(offset);
index += offset;
}
// Gotta go back to the start of the last match
index -= result.length;
return [index, result];
}
/** Remove the n-th occurrence of given pattern out of a string. */
function removeNth(str, pattern, n = 1) {
const result = findNth(str, pattern, n);
if(result[0] === -1)
return str;
return str.slice(0, result[0]) + str.slice(result[0] + result[1].length);
}
{
const str = 'This is for trails and I want to learn Js and Coding and Development';
console.log(removeNth(str, 'and', 2));
console.log(removeNth(str, /\s*and/, 2));
}
Use split
sen.split(cat, 2) // This line will divide the syntax into an array of two elements till second "and" occurrence
// ['This is for trails ', ' I want to learn Js ']
Then you need to join them to add the first and
sen.split(cat, 2).join(cat)
And to get the length
sen.split(cat, 2).join(cat).length
let str = "This is for trails and I want to learn Js and Coding and Development".split("and", 2).join("");
console.log(str);
Related
My string have a two part and separated by /
I want left side string of slash accept any string except "HAHAHA" end of word
And right side string of slash accept any string and allow use "HAHAHA" in end of string
only by Regular Expression and match function to return result parts
For example:
Accept : fooo/baarHAHAHA
Reject : fooHAHAHA/baaar
I want if string have one part, for example baarHAHAHA, accept but result like this:
string: baarHAHAHA
Group1: empty
Group2: baarHAHAHA
Have any idea?
You can try
^(\w*?)(?<!HAHAHA)\/?(\w+)$
Explanation of the above regex:
^, $ - Represents start and end of the line respectively.
(\w*?) - Represents first capturing group capturing the word characters([a-zA-Z0-9_]) zero or more times lazily.
(?<!HAHAHA) - Represents a negative look-behind not matching if the first captured group contains HAHAHA at the end.
\/? - Matches / literally zero or one time.
(\w+) - Represents second capturing group matching word characters([0-9a-zA-Z_]) one or more times.
You can find the demo of the above regex in here.
const regex = /^(\w*?)(?<!HAHAHA)\/?(\w+)$/gm;
const str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
`;
let m;
let resultString = "";
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m[1] === "")resultString = resultString.concat(`GROUP 1: empty\nGROUP 2: ${m[2]}\n`);
else resultString = resultString.concat(`GROUP 1: ${m[1]}\nGROUP 2: ${m[2]}\n`);
}
console.log(resultString);
You don't need regex for this, which is good since it is quite slow. A simple string.split() should be enough to separate the parts. Then you can just check if the word contains "HAHAHA" with the string.endsWith() method.
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
console.log(a.split('/')); // Array [ 'fooHAHAHA', 'bar' ]
console.log(b.split('/')); // Array [ 'foo', 'bar' ]
console.log(c.split('/')); // Array [ 'fooHAHAHA' ]
// therefore ...
function splitMyString(str) {
const strSplit = str.split('/');
if (strSplit.length > 1) {
if (strSplit[0].endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
Alternative non-regex solution:
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
function splitMyString(str) {
const separator = str.indexOf('/');
if (separator !== -1) {
const firstPart = str.substring(0, separator);
if (firstPart.endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
var str, re;
function match(rgx, str) {
this.str = str;
this.patt = rgx
var R = [], r;
while (r = re.exec(str)) {
R.push({
"match": r[0],
"groups": r.slice(1)
})
}
return R;
}
str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
barr/bhHAHAHA
`;
re = /(?<=\s|^)(.*?)\/(.*?HAHAHA)(?=\s)/g;
console.log(match(re, str))
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Edit: When I make this code I think to letting user to call the str and when call it, it will return the mactheds and groups. But, if I make like this.str = str and have return too, this.str will be declined.
Everything I can find by searching is people wanting to convert to sentence/title case from lower/upper/random case. That's the opposite of my problem.
What I have is already correct, I want to convert it to uppercase except for the "c" or "ac" etc. So McDonald becomes McDONALD, MacDonald becomes MacDONALD, etc.
Probably the best way is separating out the lower-case letters that occur between two upper-case letters, either before or after running toUpperCase(), but my brain is fried at the moment so I'm not sure how to go about it.
It's for an After Effects expression, controlling the display so I can have sentence case in one composition and upper case in another, from the same source layer. So I know input will be perfect.
You can try something like this:
const input = "MacDonald";
const matches = input.match(/([A-Z][a-z]*)/g);
const output = matches.length > 1 ?
matches.reduce((acc, match, index) => {
if (index === 0) {
return match;
}
return acc + match.toUpperCase();
}) :
input.toUpperCase();
First we take the input apart by matching it against a simple regular expression. The match method in the example will return ["Mac","Donald"].
Then, if there is only one match, we return it in uppercase.
In case of multiple matches, we construct the result by concatenating uppercase parts except for the first part.
Here's a version for a whole sentence:
const input = "Old MacDonald is a fine man.";
const output = input
.split(/\s/)
.map(word => {
const matches = word.match(/([A-Z][a-z]*)/g);
if (!matches || matches.length === 1) {
return word.toUpperCase();
}
return matches.reduce((acc, match, index) => {
return index === 0 ? match : acc + match.toUpperCase();
});
})
.join(' ');
// output == "OLD MacDONALD IS A FINE MAN."
Sami Hult's answer covers most of the bases, but unfortunately refuses to work in After Effects due to syntax issues and map() and reduce() not being supported, and I wanted to make one small tweak, all-capsing only the last portion rather than all but the first (to account for a possible double prefix).
So based on that code, I came up with this:
function str_uppercase(str) {
str = str.split(/\s/);
var output = [];
for (i = 0; i < str.length; i++) {
var word = str[i];
var matches = word.match(/([A-Z][a-z]*)/g);
if (!matches || matches.length === 1) {
word = word.toUpperCase();
} else {
var x = matches.length - 1;
matches[x] = matches[x].toUpperCase();
word = matches.join('');
}
output.push(word);
}
return output.join(' ');
}
console.log(str_uppercase('Old MacMcDonald Had a farm'));
// => OLD MacMcDONALD HAD A FARM
The code below assumes a string prefix to be one capital letter character followed by one or more small letter characters followed by one capital letter character and always at the beginning of the whole word.
The prefix will be retained as it is and the rest will be capitalized.
const input = [
"McDonald",
"MacDonald",
"Mcdonald",
"mcDonald",
"mcdonald"
];
// Function for converting to special uppercase
const specialUpperCase = function(item) {
// Find prefix (one or more lower case characters between upper case character - at the beginning)
const match = item.match(/^[A-Z][a-z]+[A-Z]/);
if (match) {
// If prefix, capitalize only the remaining
return match[0] + item.substr(match[0].length).toLocaleUpperCase();
}
// If no prefix, capitalize the whole string
return item.toLocaleUpperCase();
};
const output = input.map(specialUpperCase);
console.log(output);
The easiest solution would probably be to keep a list of prefixes and test if the word starts with one of these:
//Prefixes to look for
var prefixToKeep = [
"Mac",
"Mc"
];
//Selective uppercase function
function selectiveUpperCase(text) {
//Find words by wordBoundaries
return text.replace(/\b\w+\b/gim, function (word) {
//Test for prefixes
for (var prefixToKeepIndex = 0; prefixToKeepIndex < prefixToKeep.length; prefixToKeepIndex++) {
var prefix = prefixToKeep[prefixToKeepIndex];
if (word.indexOf(prefix) === 0) {
//prefix matches. Return prefix as is + rest of the word in uppercase
return word.slice(0, prefix.length) + word.slice(prefix.length).toUpperCase();
}
}
//No prefix found, return word as uppercase
return word.toUpperCase();
});
}
//TEST
var text = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on this farm he had a cow\nE-I-E-I-O\nWith a moo-moo here\nAnd a moo-moo there\nHere a moo, there a moo\nEverywhere a moo-moo\nOld MacDonald had a farm\nE-I-E-I-O ";
console.log(selectiveUpperCase(text));
EDIT 1 - Upper-Lower-Upper Test
In response to the comments, this newer version tests for Upper-Lower-Upper cases and uses its findings to determine which parts to uppercase.
//Selective uppercase function
function selectiveUpperCase(text) {
//Find words by wordBoundaries
return text.replace(/\b\w+\b/gim, function (word) {
var reg = /[A-Z]+[a-z]+[A-Z]\w+/gm;
//Test for Upper-Lower-Upper combo
if (reg.test(word) || reg.test(word)) {
//start at index 1
var l = 0;
while (l++ < word.length) {
//move up the word and test for an uppercase letter
if (word[l] === word[l].toUpperCase()) {
break;
}
l++;
//return the first slice (the prefix) as is and uppercase the rest
return word.slice(0, l) + word.slice(l).toUpperCase();
}
}
//No prefix found, return word as uppercase
return word.toUpperCase();
});
}
//TEST
var text = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on this farm he had a cow\nE-I-E-I-O\nWith a moo-moo here\nAnd a moo-moo there\nHere a moo, there a moo\nEverywhere a moo-moo\nOld McDonald had a farm\nE-I-E-I-O ";
console.log(selectiveUpperCase(text));
ES6 version with RegEx, you can try below function replaceStr()
const replaceStr = str => str.replace(/(^[A-Z])([a-z]{1,2})(.+)/,
(_, p1, p2, p3) => p1.toUpperCase() + p2 + p3.toUpperCase());
I have a function that get string, I'm looking for a way to format the 3rd word (which is number, that i want to format it with comma). any idea how to do it?
should be something like that:
function formatNumber(txt){
return txt.replace(3rd-word, formatNumber(3rd-word));
}
Match any word that consists of digits, and format it:
txt = txt.replace(/\b(\d+)\b/g, format);
using a formatting function, for example:
function format(s) {
var r = '';
while (s.length > 3) {
r = ',' + s.substr(s.length - 3) + r;
s = s.substr(0, s.length - 3);
}
return s + r;
}
Demo: http://jsfiddle.net/Guffa/5yA62/
Break it down into parts.
Create a function that transforms your word into the format you want.
Split your sentence into words.
Run that function against the appropriate word.
Put the words back into a sentence.
This does not solve your problem. You would still need to find a way to format the number as you choose, but it solves a similar problem of uppercasing the third word:
var transformNth = function(n, fn) {
return function(arr) {
arr[n] = fn(arr[n]);
return arr;
}
};
var makeWords = function(sentence) {return sentence.split(" ");};
var upperCase = function(word) {return word.toUpperCase();}
var transformSentence = function(sentence) {
// index 2 is the third word
return transformNth(2, upperCase)(makeWords(sentence)).join(" ");
}
transformSentence("I have a function that get string");
//=> "I have A function that get string"
transformSentence("I'm looking for a way to format the 3rd word");
//=> "I'm looking FOR a way to format the 3rd word"
transformSentence("which is number");
//=> "which is NUMBER"
transformSentence("that i want to format it with comma");
//=> "that i WANT to format it with comma"
transformSentence("any idea how to do it?");
//=> "any idea HOW to do it?"
transformSentence("should be something like that");
//=> "should be SOMETHING like that"
It might have problems if your sentences have some more complicated structure than single whitespace separation of words that you want to maintain...
You can get the n-th word from the sentence by splitting it up and executing a replace on the word index as specified.
Here is a demo for the code below: DEMO
var sentence = "Total is 123456789!"
var formatNumber = function(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var replaceWord = function(sentence, pos, formatterFunction) {
var matches = sentence.match(/(\b[^\s]+\b)/g);
if (pos < 0 && pos >= matches.length) {
throw "Index out of bounds: " + pos;
}
var match = matches[pos];
var bounded = new RegExp('\\b' + match + '\\b');
return sentence.replace(bounded, formatterFunction(match));
};
console.log(replaceWord(sentence, 2, formatNumber)); // Total is 123,456,789!
How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:
var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);
// trimmedString should be:
// "this is"
Anyone got ideas? I've heard something about using substring, but didn't quite understand.
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Copying Will's comment into an answer, because I found it useful:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)
I suggest to use an extension for code neatness.
Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
Prefer String.prototype.slice over the String.prototype.substring method (in substring, for some cases it gives a different result than what you expect).
Trim the string from LEFT to RIGHT:
const str = "123456789";
result = str.slice(0,5); // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"
startIndex > endIndex:
result = str.slice(5,0); // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)
Trim the string from RIGHT to LEFT: (-ve start index)
result = str.slice(-3); // "789", extracts last 3 characters
result = str.substring(-3); // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"
Little late... I had to respond. This is the simplest way.
// JavaScript
function fixedSize_JS(value, size) {
return value.padEnd(size).substring(0, size);
}
// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
return value.padEnd(size).substring(0, size);
}
// Prototype (preferred)
String.prototype.fixedSize = function(size) {
return this.padEnd(size).substring(0, size);
}
// Overloaded Prototype
function fixedSize(value, size) {
return value.fixedSize(size);
}
// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
Step by step.
.padEnd - Guarentees the length of the string
"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository."
source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring - limits to the length you need
If you choose to add ellipses, append them to the output.
I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.
Just another suggestion, removing any trailing white-space
limitStrLength = (text, max_length) => {
if(text.length > max_length - 3){
return text.substring(0, max_length).trimEnd() + "..."
}
else{
return text
}
There are several ways to do achieve this
let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);
function finalDesc(str, length){
// return str.slice(0,length);
// return str.substr(0, length);
// return str.substring(0, length);
}
You can also modify this function to get in between strings as well.
Here is my solution, which includes trimming white space too.
const trimToN = (text, maxLength, dotCount) => {
let modText = text.trim();
if (modText.length > maxLength) {
modText = text.substring(0, maxLength - dotCount);
modText = modText.padEnd(maxLength, ".");
return modText;
}
return text;
};
trimToN('Javascript', 6, 2) will return "Java.."
I think that you should use this code :-)
// sample string
const param= "Hi you know anybody like pizaa";
// You can change limit parameter(up to you)
const checkTitle = (str, limit = 17) => {
var newTitle = [];
if (param.length >= limit) {
param.split(" ").reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(" ")} ...`;
}
return param;
};
console.log(checkTitle(str));
// result : Hi you know anybody ...
See my code snippet below:
var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
if (str.endsWith(list[i])
{
str = str.replace(list[i], 'finish')
}
}
I want to replace the last occurrence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurrence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'
Well, if the string really ends with the pattern, you could do this:
str = str.replace(new RegExp(list[i] + '$'), 'finish');
You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.
n = str.lastIndexOf(list[i]);
if (n >= 0 && n + list[i].length >= str.length) {
str = str.substring(0, n) + "finish";
}
...or along those lines.
Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:
function removeLastInstance(badtext, str) {
var charpos = str.lastIndexOf(badtext);
if (charpos<0) return str;
ptone = str.substring(0,charpos);
pttwo = str.substring(charpos+(badtext.length));
return (ptone+pttwo);
}
I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)
Here's a method that only uses splitting and joining. It's a little more readable so thought it was worth sharing:
String.prototype.replaceLast = function (what, replacement) {
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
Thought I'd answer here since this came up first in my Google search and there's no answer (outside of Matt's creative answer :)) that generically replaces the last occurrence of a string of characters when the text to replace might not be at the end of the string.
if (!String.prototype.replaceLast) {
String.prototype.replaceLast = function(find, replace) {
var index = this.lastIndexOf(find);
if (index >= 0) {
return this.substring(0, index) + replace + this.substring(index + find.length);
}
return this.toString();
};
}
var str = 'one two, one three, one four, one';
// outputs: one two, one three, one four, finish
console.log(str.replaceLast('one', 'finish'));
// outputs: one two, one three, one four; one
console.log(str.replaceLast(',', ';'));
A simple answer without any regex would be:
str = str.substr(0, str.lastIndexOf(list[i])) + 'finish'
I did not like any of the answers above and came up with the below
function isString(variable) {
return typeof (variable) === 'string';
}
function replaceLastOccurrenceInString(input, find, replaceWith) {
if (!isString(input) || !isString(find) || !isString(replaceWith)) {
// returns input on invalid arguments
return input;
}
const lastIndex = input.lastIndexOf(find);
if (lastIndex < 0) {
return input;
}
return input.substr(0, lastIndex) + replaceWith + input.substr(lastIndex + find.length);
}
Usage:
const input = 'ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty';
const find = 'teen';
const replaceWith = 'teenhundred';
const output = replaceLastOccurrenceInString(input, find, replaceWith);
console.log(output);
// output: ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteenhundred twenty
Hope that helps!
Couldn't you just reverse the string and replace only the first occurrence of the reversed search pattern? I'm thinking . . .
var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
if (str.endsWith(list[i])
{
var reversedHaystack = str.split('').reverse().join('');
var reversedNeedle = list[i].split('').reverse().join('');
reversedHaystack = reversedHaystack.replace(reversedNeedle, 'hsinif');
str = reversedHaystack.split('').reverse().join('');
}
}
If speed is important, use this:
/**
* Replace last occurrence of a string with another string
* x - the initial string
* y - string to replace
* z - string that will replace
*/
function replaceLast(x, y, z){
var a = x.split("");
var length = y.length;
if(x.lastIndexOf(y) != -1) {
for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
if(i == x.lastIndexOf(y)) {
a[i] = z;
}
else {
delete a[i];
}
}
}
return a.join("");
}
It's faster than using RegExp.
Simple solution would be to use substring method.
Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method
str = str.substring(0, str.length - list[i].length) + "finish"
function replaceLast(text, searchValue, replaceValue) {
const lastOccurrenceIndex = text.lastIndexOf(searchValue)
return `${
text.slice(0, lastOccurrenceIndex)
}${
replaceValue
}${
text.slice(lastOccurrenceIndex + searchValue.length)
}`
}
A negative lookahead solution:
str.replace(/(one)(?!.*\1)/, 'finish')
An explanation provided by the site regex101.com,
/(one)(?!.*\1)/
1st Capturing Group (one)
one - matches the characters one literally (case sensitive)
Negative Lookahead (?!.*\1)
Assert that the Regex below does not match
. matches any character (except for line terminators)
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\1 matches the same text as most recently matched by the 1st capturing group
Old fashioned and big code but efficient as possible:
function replaceLast(origin,text){
textLenght = text.length;
originLen = origin.length
if(textLenght == 0)
return origin;
start = originLen-textLenght;
if(start < 0){
return origin;
}
if(start == 0){
return "";
}
for(i = start; i >= 0; i--){
k = 0;
while(origin[i+k] == text[k]){
k++
if(k == textLenght)
break;
}
if(k == textLenght)
break;
}
//not founded
if(k != textLenght)
return origin;
//founded and i starts on correct and i+k is the first char after
end = origin.substring(i+k,originLen);
if(i == 0)
return end;
else{
start = origin.substring(0,i)
return (start + end);
}
}
I would suggest using the replace-last npm package.
var str = 'one two, one three, one four, one';
var result = replaceLast(str, 'one', 'finish');
console.log(result);
<script src="https://unpkg.com/replace-last#latest/replaceLast.js"></script>
This works for string and regex replacements.
if (string.search(searchstring)>-1) {
stringnew=((text.split("").reverse().join("")).replace(searchstring,
subststring).split("").reverse().join(""))
}
//with var string= "sdgu()ert(dhfj ) he ) gfrt"
//var searchstring="f"
//var subststring="X"
//var stringnew=""
//results in
//string : sdgu()ert(dhfj ) he ) gfrt
//stringnew : sdgu()ert(dhfj ) he ) gXrt
str = (str + '?').replace(list[i] + '?', 'finish');