This question already has answers here:
Find and replace nth occurrence of [bracketed] expression in string
(4 answers)
Closed 5 years ago.
This question been asked before, but I did not succeed in solving the problem.
I have a string that contains numbers, e.g.
var stringWithNumbers = "bla_3_bla_14_bla_5";
I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than
var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);
This only changes the first number.
It was suggested to use back references like $1, but this did not help me.
The result should, for example, be
"bla_3_bla_xy_bla_5" //changed 2nd occurence
You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:
var mystr = 'bla_3_bla_14_bla_5';
function replaceOccurrence(string, regex, n, replace) {
var i = 0;
return string.replace(regex, function(match) {
i+=1;
if(i===n) return replace;
return match;
});
}
console.log(
replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)
Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.
var stringWithNumbers = "bla_3_bla_14_bla_5";
var n = 1;
var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);
console.log(changedString);
Related
This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";
Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2
Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I want to get the page number out if these possible strings:
$scope.projects.next can equal...
string 1) /api/project/?currentuser=false&page=2
string 2)
/api/project/?page=2
I have tried this:
$scope.projects.next.split('=')[1].indexOf("page")
However, this only works on string 2. How can I change this to make sure it finds the page number no matter what position or future arguments that could be added?
I have also tried:
$scope.projects.next.indexOf("page")
but this gives 52 no idea why.
You can use regex:
/page=([0-9]+)/.exec($scope.projects.next)[1]
That uses a regular expression with a capture group (the bit in ()) for the page number, and captures one or more digits after page=. The result is an array, where the first element is the whole match, and the second is the capture group (that's why we have [1] at the end).
please see here: http://jsbin.com/gizalo/1/edit
function to get parametr from string
function getParameterByName(name, string) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(string);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Controller
app.controller('firstCtrl', function($scope){
var stringa="/api/project/?currentuser=false&page=2";
var stringb="/api/project/?page=2";
$scope.a = getParameterByName('page', stringa);
$scope.b = getParameterByName('page', stringb);
});
The problem is that in the first url there are two = signs so your index would be out by 1 on the first url
$scope.projects.next.split('page=')[1]
This has absolutely nothing to do with AngularJS. But it's also simple, so why not answer. Splitting on a character splits on EVERY instance of that character. Your top string is going to end up being ['/api/project/?currentuser', 'false&page', '2'], so getting the position of [1]('page') isn't useful. Split it on ? instead.
var start = $scope.projects.next.indexOf("page=");
var end = $scope.projects.next.indexOf("&");
var page;
if(end == -1) {
page = $scope.projects.next.substring(start+5);
} else {
page = $scope.projects.next.substring(start+5, end);
}
This would also work for ?page=17&test=2
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.
This question already has an answer here:
use regex to replace all but first occurrence of a substring of blanks
(1 answer)
Closed 9 years ago.
How can I make a Regex which replaces all occurrences of a word but the first?
I have a webpage with loads of text and a header at the top. I want to make a regex which replaces all occurrences of a word but the first because I don't want the header to change.
var count = 0;
text = text.replace(myRegex, function(match) {
count++;
if(count==1) {
return match;
}
else {
return myReplacedValue;
}
});
You could do this:
var i = 0;
"foo foo foo".replace(/foo/g, function(captured/*, offset, originalString */) {
if ( i++ ) {
return 'bar';
}
return captured;
});
great answer abstract... i have never seen replace used like that before
heres a nice cluttered version..
text = text.replace(/boo/g, function(match) {return (++count==1)?match:myReplacedValue});