In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )
Related
I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.
You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego
You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')
For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)
This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);
I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
I have a string that returns 04/01/2014 , my problem now is how can I change it using jquery so that the string will become 2014-04-01 ?
var stringDate = '04/01/2014';
any help will be appreciated, thanks in advance
You can split a JavaScript string into parts delimited by a pattern (in your case, /), and you can combine them back together however you like using another delimiter.
For instance:
var str = "04/01/2014";
var parts = str.split("/");
var result = parts[2] + "-" + parts[0] + "-" + parts[1];
make a DateTime() variable then you can manipiulate it how you want
In Javascript, I have a string for a path that looks like:
/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4
The prefix may or may not be there for each level. I need to create a new string which eliminates the prefix on each folder level, something like:
/Level1/Level2/Level3/Level4
OK. I've done something like the following, but I think perhaps with regex it could be made more compact. How could I do that?
var aa = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4"
var bb = aa.split("/").filter(String);
var reconstructed = "";
for( var index in bb )
{
var dirNames = bb[index].split(":");
if(dirNames.length==1) reconstructed += "/" + dirNames[0];
else if(dirNames.length==2) reconstructed += "/" + dirNames[1];
}
You can use regex like this:
var str = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var out = str.replace(/\/[^:\/]+:/g, "/");
alert(out);
This matches:
/
followed by one or more characters that is not a : or a /
followed by a :
and replaces all that with a / effectively eliminating the xxx:
Demo here: http://jsfiddle.net/jfriend00/hbUkz/
Like this:
var bb = aa.replace(/\/[a-z]+:/g, '/');
Change the [a-z] to include any characters that might appear in the prefix, or just use [^\/:].
var a = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var b = a.replace(/\/[^\/]*:/g, "/");
aa = aa.replace(/\/[^:\/]\:/g, "/");
This function will replace every occurence of "/xxx:" by "/" using a RE, where xxx: is a prefix.
I am trying to match a part of the string and it should be NOT case sensitive. I have the following code but I never get the replaced string.
var name = 'Mohammad Azam'
var result = name.replace('/' + searchText + '/gi', "<b>" + searchText + "</b>");
The searchText variable will be "moha" or "mo" or "moh".
How can I get the matching thing in bold tags.
/pattern/ has meaning when it's put in as a literal, not if you construct string like that. (I am not 100% sure on that.)
Try
var name = 'Mohammad Azam';
var searchText = 'moha';
var result = name.replace(new RegExp('(' + searchText + ')', 'gi'), "<b>$1</b>");
//result is <b>Moha</b>mmad Azam
EDIT:
Added the demo page for the above code.
Demo →
Code
I think you're looking for new RegExp, which creates a dynamic regular expression - what you're trying to do now is match a string ( not a regexp object ) :
var name = 'Mohammad Azam', searchText='moha';
var result = name.replace(new RegExp(searchText, 'gi'), "" + searchText + ""); result
EDIT: Actually, this is probably what you were looking for, nevermind ^
var name = 'Mohammad Azam', searchText='moha';
name.match( new RegExp( searchText , 'gi' ) )[0]
name // "Moha"