Replace substring with edited substring [duplicate] - javascript

This question already has answers here:
Why isn't this split in javascript working?
(2 answers)
Closed 8 years ago.
please, could you help me with my task: I need to replace part of string and probably the best way is regular expression but I don't know, how to make it working. I want to do this:
http://someweb.com/section/&limit=10&page=2
replace page=2 with page=3 so string will be:
http://someweb.com/section/&limit=10&page=3
I tried to do something like this:
// set string in t variable
t.replace('/page=[0-9]/', 'page=$1++') });
Thank you very much for your help :)

In our case first argument should be regexp, but in your variant this is string '/page=[0-9]/' (remove '). In replace you can pass function as second argument, and do with matched data what you want. (for example add +1 to page=)
var str = "http://someweb.com/section/&limit=10&page=2";
str.replace(/page=(\d+)/, function (match, page) {
return 'page=' + (+page + 1); // plus before page converts string to number
});
Example

You can also try below code.
var url = "http://someweb.com/section/&limit=10&page=2",
reExp = /page=([0-9])+/,
result = reExp.exec(url);
url = url.replace(reExp, 'page=' + (+result[1] + 1));
console.log(url)

Related

find and replace '%20' with a space in a string javascript [duplicate]

This question already has answers here:
Javascript replace all "%20" with a space
(7 answers)
Closed 4 years ago.
I'm having some trouble trying to figure this out,
basically I have a url string like so this%20is%20a%20string now what I want to do is find and replace all instances of %20 and replace with a space so the string then becomes this is a string.
Now I've tried to do something like this..
if(string.includes('%20')) {
const arr = str.split('%20');
}
which splits the string into an array, but I'm not sure how I can then turn the array of seperate strings into a full string with spaces between each word.
Any help would be appreciated.
Using regex,
str.replace(/%20/g, ' ');
Just use join:
str.split('%20').join(" ")
let val = "this%20is%20a%20string".replace(/%20/g, ' ');
alert(val);
replace

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

Javascript Regex - Match everything after string [duplicate]

This question already has answers here:
Remove querystring from URL
(11 answers)
Closed 6 years ago.
I'm trying to use JS regex to drop everything after a string in my url. For example www.myurl/one/two/three/?a=b&c=d I want to drop everything after the string "three/". How would I write a regex to match this?
Try this one:
function getPathFromUrl(url) {
return url.split("?")[0];
}
var url = 'www.myurl/one/two/three/?a=b&c=d';
var result = getPathFromUrl(url);
alert(result);
Here's one quick way.
var str = 'www.myurl/one/two/three/?a=b&c=d'
var newStr = str.replace(/(.*\/three\/).*/, '$1')
alert(newStr)
Use built-in ability to manipulate URLs.
var a = document.createElement('a');
a.href = "http://www.myurl/one/two/three/?a=b&c=d";
a.search = '';
console.log(a.href);
Notes:
The search property of the a element refers to the portion starting with the question mark.
The http:// is required here; otherwise, the URL will be interpreted as relative to the current URL.
If you would prefer to use a regexp, then you could erase everything starting with the question mark:
"www.myurl/one/two/three/?a=b&c=d".replace(/\?.*/, '')
Or, you could match what you DO want to keep, such as everything up to the question mark, using:
"www.myurl/one/two/three/?a=b&c=d".match(/.*(?=\?)/)[0]
You need the [0] since match returns an array, whose first element is the entire match. The ?= here is a look-ahead. Actually that is the same as
"www.myurl/one/two/three/?a=b&c=d".match(/[^?]+/)[0]
Or, if you want to match up to three/ specifically:
"www.myurl/one/two/three/?a=b&c=d".match(/.*three\//)[0]
Or basicaly with methods of String and Array :
var string = "www.myurl/one/two/three/?a=b&c=d";
var array = string.split('/');
array.pop();
var result = array.join("/");
console.log(result); //www.myurl/one/two/three

Getting substring starting by char [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
I know that js substring method accept number parameters but what if I need to get a part of string beginning with ?. So the method must accept a char value for beginning position. How can I do this?
http://localhost:8080/new_prog_24/search.action?country=&city=&sex=1&beginage=16&endage=65&children=&confession=0#2
You could use the indexOf method so that you know where is the "?" char.
var test = "is this a test? Yes it is!";
var startAt = test.indexOf('?') + 1; // + 1 so that '?' is not returned
test.substring(startAt);
Something like this should get you the results (unless I am understanding your question incorrectly, apologies if I did):-
index = myString.indexOf("?");
var mysubString = "";
if(index == 0) //<--- only for strings that are beginning with a "?"
{
mysubString = myString.Substring(1, myString.length);
}
this should get you a string that starts with a "?" but without displaying the "?" as part of your substring...until the end of the string.

javascript: is there any elegant way to check if string contains any of characters given in an array [duplicate]

This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}

Categories

Resources