How to increase each number in a string? - javascript

I need to search a string for any numbers in it and increase the numbers by 1. So that this 'sermon[thesis][1][name][2]' becomes 'sermon[thesis][2][name][3]'.

This will do the trick:
"sermon[thesis][1][name][2]".replace(/\[(\d+)\]/g, function(match, number) {
return "[" + (Number(number) + 1) + "]";
});
Working demo: jsFiddle.
EDIT:
To increment the last number, you would add a dollar sign $ before the last /, here's a demo: jsFiddle.

You can use replace, it can actually take a function as the replacement "string".
var str = 'sermon[thesis][1][name][2]';
str = str.replace(/(\d+)/g, function(a){
return parseInt(a,10) + 1;
});
console.log(str); //'sermon[thesis][2][name][3]'

You can do something like this:
var str = "sermon[thesis][1][name][2]";
var newStr = str.replace(new RegExp("\\d+", "g"), function (n) {
return parseInt(a, 10) + 1;
});
Basicly, the function would be called with the text been captured by the expression \d+,the text return from the function would be use to replace the captured text.

You can use the replace() function to match any number with a regular expression and then return that value incremented by 1 to replace it:
var string = '[1][2]';
string.replace(/[0-9]+/g,function(e){return parseInt(e,10)+1})); //Returns [2][3]
Working Example

Related

Keep only one occurrence of substring in a string

I'm looking for a function that removes all occurrences of a substring in a string except the first one, so for example
function keepFirst(str, substr) { ... }
keepFirst("This $ is some text $.", "$");
should return: This $ is some text .
I could do it using split() and then for(){}, but is there a nicer solution?
This could be the shortest code that is somewhat efficient. It uses destructuring assignment.
function keepFirst(str, substr) {
const [
first,
...rest
] = str.split(substr);
return first + (rest.length
? substr + rest.join("")
: "");
}
This solution finds the index of the first occurence of rep and removes all of the reps after it.
console.log(keepFirst("This $ is some text $$ with $ signs.", "$"));
function keepFirst(str, rep) {
var fInd = str.indexOf(rep);
var first = str.substring(0, fInd + rep.length);
var rest = str.substring(fInd + rep.length);
return first + rest.replace(
new RegExp(rep.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), 'g'),
'');
}

How to account for punctuation and uppercase while counting the number of occurrences of a string in a sentence

I'm writing a function but cannot figure out how to account for upper case letter and punctuation.
My function is :
function countWords(word, string) {
var subStr = string.split(word);
return subStr.length - 1;
}
And it works when I try to test is with wordCount("hey","this is code hey"), but not if I try ("HEY", "this is code hey")
I tried
var subStr= string.toUpperCase().split(word)
but it will not work with lower case letters anymore.
Why can't you try like this.
function countWords(word, string) {
word= word.toLowerCase();
string=string.toLowerCase();
var subStr = string.split(word);
return subStr.length - 1;
}
So that whatever values we sent it will be converted into lower case then it will split.
Does it makes sense right?
Try this :
function countWords(word, string) {
var subStr = string.toLowerCase().split(word.toLowerCase());
return subStr.length - 1;
}
$(document).ready(function(){
$('#result').html(countWords("HEY","this is code hey"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
Try sending the parameter to either all upper or lower cases first so that it matches the case of the string you are comparing it to. For example,
function countWords(word.toLowerCase, string.toLowerCase)
That way the search is evaluated regardless of case.
You could use a regex with the i and g modifier (case insensitive/match all) and match, then return the length:
function wordCount(search, txt) {
var regex = new RegExp("\\W" + search + "\\W|\\W" + search, "ig");
var match = txt.match(regex);
return match ? match.length : 0;
}
console.log(wordCount("hey","this is code heyHey HEY hey")); // 2
If you want to have heyHey as 2 matches, simply remove |\\W" + search from the regex

how to replace multiple special character in a number?

I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle

replace number after underscore

I nee to replace all numbers after underline inside a string.
I think that I can use Regex, but I don't know how to use Regex Syntax
See an example of my string:
milton_0
milton_1
If that is the standard format, You can use split()
var str = 'milton_1';
alert(str.split('_')[1]);
You don't need regex for this. The following code in enough
var str = "milton_0";
str = str.substring(0,str.indexOf("_"));
I'm not sure how specific or broad you want to be, but you can try this:
var starter = "milton_1";
var specialVal = "asdf";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/
This will match a string starting with "milton_" and ending with digits. It replaces any digits after the "_" with the specialVal value.
An example of simply incrementing that number is:
var starter = "milton_1";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1, p2) {
return p1 + (+p2 + 1);
});
console.log(replaced);
http://jsfiddle.net/ne4cD/2/
UPDATE:
If the "milton" part isn't static, then you're really only targeting the "_" with digits after it. So something like this:
var starter = "asdfkjlasdfjksadf_1";
var specialVal = "asdf";
var re = /(_)(\d+)/g;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/3/
And maybe a little better to see: http://jsfiddle.net/ne4cD/4/
First of all you need them as list for handling easily.
var listOfStrings = yourStringObject('whateverYourCharacterUnderEachWord').ToList<string>();
After that you need to get rid of number for each string in the list and add what you want.
foreach(string word in listOfStrings){
word = word.Substring(0,word.IndexOf('_')+1);
word = word + "characterThatYouWantToAddHere"
}

Replace substring in string with range in JavaScript

How can I replace a substring of a string given the starting position and the length?
I was hoping for something like this:
var string = "This is a test string";
string.replace(10, 4, "replacement");
so that string would equal
"this is a replacement string"
..but I can't find anything like that.
Any help appreciated.
Like this:
var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length);
You can add it to the string's prototype:
String.prototype.splice = function(start,length,replacement) {
return this.substr(0,start)+replacement+this.substr(start+length);
}
(I call this splice because it is very similar to the Array function of the same name)
For what it's worth, this function will replace based on two indices instead of first index and length.
splice: function(specimen, start, end, replacement) {
// string to modify, start index, end index, and what to replace that selection with
var head = specimen.substring(0,start);
var body = specimen.substring(start, end + 1); // +1 to include last character
var tail = specimen.substring(end + 1, specimen.length);
var result = head + replacement + tail;
return result;
}
Short RegExp version:
str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word);
Example:
String.prototype.sreplace = function(start, length, word) {
return this.replace(
new RegExp("^(.{" + start + "}).{" + length + "}"),
"$1" + word);
};
"This is a test string".sreplace(10, 4, "replacement");
// "This is a replacement string"
DEMO: http://jsfiddle.net/9zP7D/
The Underscore String library has a splice method which works exactly as you specified.
_("This is a test string").splice(10, 4, 'replacement');
=> "This is a replacement string"
There are a lot of other useful functions in the library as well. It clocks in at 8kb and is available on cdnjs.

Categories