I have this span on my website with these values.
<span>1,4,4,7,5,9,10</span>
I want to use jquery to delete the "1," (or what ever the first number is) from the beginning of the string and add ",12" at the end (or any other number instead of 12) so it would look like this:
<span>4,4,7,5,9,10,12</span>
How can I do this with jquery or java script ?
<span id="myText">1,4,4,7,5,9,10</span>
JS:
var text = $('#myText').html().split(',').slice(1);
text.push('12');
$('#myText').html(text.join(','));
http://jsfiddle.net/samliew/RD6W8/7/
$('span').text(function(i, t) {
return t.replace(/\d+,/, '') + ',12';
})
http://jsfiddle.net/dnkEV/
You can use split or regular expressions with string.replace
Here's how to use split:
var arr = '1,4,4,7,5,9,10'.split(',');
arr.shift();
arr.push('12');
var result = arr.join(',');
Or with regular expressions (not a very readable one I concede):
'1,4,4,7,5,9,10'.replace(/^\d+,(.*)$/, '$1,12')
Using DOM API, you can do this:
var tn = span.firstChild;
tn.deleteData(0, tn.data.indexOf(",") + 1);
tn.data += ",12";
http://jsfiddle.net/KMzau/
Or like this:
var tn = span.firstChild;
tn.data = tn.data.slice(tn.data.indexOf(",") + 1) + ",12";
Related
I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij
I want to remove the last parameter in the href of a specific tag using jquery
for example replace href="app/controller/action/05/04/2014"
by href="app/controller/action/05/04"
Try using the String.lastIndexOf() and String.substring() in this context to achieve what you want,
var xText ="app/controller/action/05/04/2014";
xText = xText.substring(0,xText.lastIndexOf('/'));
DEMO
if you know which value you need to change ,than you can use replace:
var str = "app/controller/action/05/04/2014";
var res = str.replace("2014","04");
or else you can use array and change / update last value in array:
var str = "app/controller/action/05/04/2014";
var res = str.split("/");
We can use a regular expression replace which will be the fastest, compared to substring/slice.
var hreftxt ="app/controller/action/05/04/2014";
hreftxt = hreftxt.replace(/\/[^\/]*$/,"");
In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end
Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);
I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;
Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.
You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/
Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);
How do I remove everything before /post in this string below and add my own address using Javascript/JQuery
showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
I want it to appear like this:
http://mydomain.com/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
var str = 'showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500';
str = 'http://mydomain.com' + str.split('&dataFile=')[1];
Example: http://jsfiddle.net/52z2z/
Here it splits the string on '&dataFile=', gets the last item in the resulting Array, and concatenates it do your domain.
You could also do this in Javascript using regular expressions:
var url = "showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500";
var matches = url.match(/dataFile=(.*)/);
var what_you_need = "http://mydomain.com" + matches[1];
HTH