I've tried fiddling with
replace(/_([^_]*)$/,replacement+'$1')
from another post but can't get it to work
I have a string:
<div class="plus"></div><div class="details"></div>text1/text2
that I want to transform into
<div class="plus"></div><div class="details"></div>text1/<br>text2
but I keep getting the / in /div replaced as well
Anyone?
Edit: To be clear I want to replace the last
"/"
with
"/<br>"
only the last occurance.
I dunno... maybe I'm better off going back in my code and try to replace the slash before prepending with html...
Use lastIndexOf() method
var index = str.lastIndexOf('/');
str = str.substr(0, index + 1) + "<br>" + str.substr(index + 1);
Here is the fiddle
Try
'<div class="plus"></div><div class="details"></div>text1/text2'.replace(/(\/)([^\/]*)$/, '$1' + '<br />' + '$2' )
If you're not trying to capture the slash in the back-reference, add the slash into the text itself:
replace(/_([^_]*)$/,replacement+'$1/')
-----------------------------------^
It's easier to do that using string methods:
var index = str.lastIndexOf('/');
str = str.substr(0, index) + str.substr(index + 1);
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 have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";
I need help in writing regular expression:
part of my string is fixed and another part of its variable.
only if fixed AND variable string exist i need to alter the string other wise no.
Fixed string:example: AA.BBB.COM
Variable string (may or mayn't exist ): US, but if exist it will be always two letter string with any combination of letter.
In below string if I have variable two letter string exist I want to append “.new”
1 ) https://XY**.US**.AA.BBB.COM
Output: https:// XYZ12**.US.NEW**.AA.BBB.COM
2 ) https://XY.UK.AA.BBB.COM
Output: https:// XYZ12.UK.NEW.AA.BBB.COM
3) https://XY.AA.BBB.COM (no variable string so no change)
Output: https:// XY.AA.BBB.COM
Thanks for your help .
Raghav
Something like the following should get you started, there are other methods. Splitting and parsing might suit better depending on your real requirements:
var s = 'https://XY.US.AA.BBB.COM';
var t = 'https://XY.UK.AA.BBB.COM';
var u = 'https://XY.AA.BBB.COM';
var re = /(\.)(UK|US)(\.)/;
alert(
s.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
t.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
u.replace(re, '$1' + '$2' + '.NEW' + '$3')
);
Removing %20 in get method?
var c=new Array(a);
(eg: a={"1","2"}) window.location="my_details.html?"+ c + "_";
and in my_details.html :
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + list + "llll " );
and in "list" its dusplaying me "1%202";
How can I remove this %20 =space value ??
Thanks
just use this:
alert("dataaaaaaaaaaaa " + decodeURIComponent(list) + "llll " );
This should decode the %20 to space
look here: http://www.w3schools.com/jsref/jsref_decodeURIComponent.asp
If there is a space in the parameter(s), then the %20 (URL Encoding) is necessary. You cannot pass a space in a GET request.
If you need to avoid this, use POST.
As far as I can see the problem is being introduced at this line:
window.location="my_details.html?"+ c + "_";
This could be written as:
window.location="my_details.html?"+ c.toString() + "_";
The default .toString() of a JavaScript Array would be to use a delimiter of ,, i.e.
var str = ["1", "2", "3"].toString(); // 1,2,3
In you example it appears that the delimiter being used is a space. This would have been changed by something changing the default behaviour of .toString() on the Array.prototype. Try using the following:
window.location="my_details.html?"+ c.join(",") + "_";
Better to use replace() method to replace %20 to space
list.replace("%20"," ");
This is the function I am working with:
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ','-');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
I can't figure out for the life of me why this function replaces the first space in h1name string with a hyphen, but not any of the subsequent ones. I tried unescaping and escaping (and then replacing %20 it stumbles upon with hyphens, but that did the same thing). I tried regular expressions for catchall whitespace and that did the same thing. I feel like I am not seeing something super fundamental here.
You need to specify a global regular expression. Otherwise it only matches the first occurrence.
// regular expression
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(/\s+/g, '-'); // matches all whitespace
// use / /g to match a single space
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
// firefox only
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ', '-', 'g');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
stuff = h1name.toLowerCase().replace(/ /g, '-');
The replace function was designed to only replace the first instance of the string you are searching for. If you want to replace all instances, then using regular expressions would work better.
take a look at this page for more information.
If you were trying to replace all spaces with - your close but not quite there
The replace function in JavaScript only replaces the first value it finds that matches and quits. Here is a replaceAll function.
stuff = h1name.toLowerCase().replace(' ' + /g, '-');
alert(stuff); //make sure this is what you want
the /g specifies replace all.