Replace nth word in sentence - javascript

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!

Related

JavaScript Convert Names to Uppercase, Except Mc/Mac/etc

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

How to replace a character with an specific indexOf to uppercase in a string?

Im trying to replace a character at a specific indexOf to uppercase.
My string is a surname plus the first letter in the last name,
looking like this: "lovisa t".
I check the position with this and it gives me the right place in the string. So the second gives me 8(in this case).
first = texten.indexOf(" ");
second = texten.indexOf(" ", first + 1);
And with this I replace the first letter to uppercase.
var name = texten.substring(0, second);
name=name.replace(/^./, name[0].toUpperCase());
But how do I replace the character at "second" to uppercase?
I tested with
name=name.replace(/.$/, name[second].toUpperCase());
But it did´t work, so any input really appreciated, thanks.
Your error is the second letter isn't in position 8, but 7.
Also this second = texten.indexOf(" ", first + 1); gives -1, not 8, because you do not have a two spaces in your string.
If you know that the string is always in the format surname space oneLetter and you want to capitalize the first letter and the last letter you can simply do this:
var name = 'something s';
name = name[0].toUpperCase() + name.substring(1, name.length - 1) + name[name.length -1].toUpperCase();
console.log(name)
Here's a version that does exactly what your question title asks for: It uppercases a specific index in a string.
function upperCaseAt(str, i) {
return str.substr(0, i) + str.charAt(i).toUpperCase() + str.substr(i + 1);
}
var str = 'lovisa t';
var i = str.indexOf(' ');
console.log(upperCaseAt(str, i + 1));
However, if you want to look for specific patterns in the string, you don't need to deal with indices.
var str = 'lovisa t';
console.log(str.replace(/.$/, function (m0) { return m0.toUpperCase(); }));
This version uses a regex to find the last character in a string and a replacement function to uppercase the match.
var str = 'lovisa t';
console.log(str.replace(/ [a-z]/, function (m0) { return m0.toUpperCase(); }));
This version is similar but instead of looking for the last character, it looks for a space followed by a lowercase letter.
var str = 'lovisa t';
console.log(str.replace(/(?:^|\s)\S/g, function (m0) { return m0.toUpperCase(); }));
Finally, here we're looking for (and uppercasing) all non-space characters that are preceded by the beginning of the string or a space character; i.e. we're uppercasing the start of each (space-separated) word.
All can be done by regex replace.
"lovisa t".replace(/(^|\s)\w/g, s=>s.toUpperCase());
Try this one (if it will be helpfull, better move constants to other place, due performance issues(yes, regexp creation is not fast)):
function normalize(str){
var LOW_DASH = /\_/g;
var NORMAL_TEXT_REGEXP = /([a-z])([A-Z])/g;
if(!str)str = '';
if(str.indexOf('_') > -1) {
str = str.replace(LOW_DASH, ' ');
}
if(str.match(NORMAL_TEXT_REGEXP)) {
str = str.replace(NORMAL_TEXT_REGEXP, '$1 $2');
}
if(str.indexOf(' ') > -1) {
var p = str.split(' ');
var out = '';
for (var i = 0; i < p.length; i++) {
if (!p[i])continue;
out += p[i].charAt(0).toUpperCase() + p[i].substring(1) + (i !== p.length - 1 ? ' ' : '');
}
return out;
} else {
return str.charAt(0).toUpperCase() + str.substring(1);
}
}
console.log(normalize('firstLast'));//First Last
console.log(normalize('first last'));//First Last
console.log(normalize('first_last'));//First Last

JavaScript split and join

I have a string, 15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt, I'd like to make it looks like 15.Prototypal...-Slider.txt
The length of the text is 56, how can I keep the first 12 letters and 10 last letters (incuding punctuation marks) and replace the others to ...
I don't really know how to commence the code, I made something like
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
str.split("// ",1);
although this gives me what I need, how do I have the results base on letters not words.
You can use str.slice().
function middleEllipsis(str, a, b) {
if (str.length > a + b)
return str.slice(0, a) + '...' + str.slice(-b);
else
return str;
}
middleEllipsis("15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt", 12, 10);
// "15.Prototypa...Slider.txt"
middleEllipsis("mpchc64.mov", 12, 10);
// "mpchc64.mov"
This function will do what you ask for:
function fixString(str) {
var LEN_PREFIX = 12;
var LEN_SUFFIX = 10;
if (str.length < LEN_PREFIX + LEN_SUFFIX) { return str; }
return str.substr(0, LEN_PREFIX) + '...' + str.substr(str.length - LEN_SUFFIX - 1);
}
You can adjust the LEN_PREFIX and LEN_SUFFIX as needed, but I've the values you specified in your post. You could also make the function more generic by making the prefix and suffix length input arguments to your function:
function fixString(str, prefixLength, suffixLength) {
if (str.length < prefixLength + suffixLength) { return str; }
return str.substr(0, prefixLength) + '...' + str.substr(str.length - suffixLength - 1);
}
I'd like to make it looks like 15.Prototypal...-Slider.txt
LIVE DEMO
No matter how long are the suffixed and prefixed texts, this will get the desired:
var str = "15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt",
sp = str.split('-'),
newStr = str;
if(sp.length>1) newStr = sp[0]+'...-'+ sp.pop() ;
alert( newStr ); //15.Prototypal...-Slider.txt
Splitting the string at - and using .pop() method to retrieve the last Array value from the splitted String.
Instead of splitting the string at some defined positions it'll also handle strings like:
11.jQuery-infinite-loop-a-Gallery.txt returning: 11.jQuery...-Gallery.txt
Here's another option. Note that this keeps the first 13 characters and last 11 because that's what you gave in your example.:
var shortenedStr = str.substr(0, 13) + '...' + str.substring(str.length - 11);
You could use the javascript substring command to find out what you want.
If you string is always 56 characters you could do something like this:
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
var newstr = str.substring(0,11) + "..." + str.substring(45,55)
if your string varies in length I would highly recommend finding the length of the string first, and then doing the substring.
have a look at: http://www.w3schools.com/jsref/jsref_substring.asp

How to trim a string to N chars in Javascript?

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 ...

JavaScript: replace last occurrence of text in a string

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

Categories