How do I delete a '_' prefix on a variable using jQuery? - javascript

I have a variable that reads as _123456 and I need to delete the underscore prefix on this variable before storing it to a field. How do I do this?
var value = "_123456"

value.substr(1)
No need for jQuery!

This is just generic Javascript, not specific to jQuery. You'd do something like this:
var result = value.substring(1);
Or...
var result = value.replace(/^_/, '');
Or... (if there can be more than one underscore)
var result = value.replace(/^_+/, '');

var value = "_123456"
var trimmed = value.substring(1); // "123456"

[not recommended]
To do this with jQuery (and an if):
var element = $('<div></div>');
var text = "_123456";
for(var i = 0; i < text.length; i++) {
if ( i > 0 ) {
element.append('<span>' + text[i] + '</span>');
}
}
var trimmed = element.text();
I tried element.remove(':first') instead of the if, but it didn't seem to work. No idea why.

FYI - If the underscore is after the digits then you could use parseInt()
var value = "123456_"
So for example parseInt("123456_") will return the number 123456.

Related

How can i split strings that has prefix and suffix in Javascript?

I have string that is stored in a variable in this form :
var c = "<p>Let's try with single inputs : *[]*</p>"
I can easily split and convert the *[]* into <span> using this method [a]:
var res = c.split("*[]*");
if(res.length > 1){
var strContent = res[0];
var inptSoal = ' <span id="content-input" class="al question mb-0">[ ]</span> ';
strContent += inptSoal;
strContent += res[1];
c = strContent;
} return c;
But now, let's say that i have this form of string [b] :
var c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
How can i split (and convert) every *[ and ]* (that has strings inside of it) into HTML <span> element? Thanks in advance
EDIT
To make it clearer, using the method i write above ([a]) it will return this in my website :
What i want to do is to return the same result if the condition is like the second form ([b]) i mentioned above. How can i achieve this?
SOLVED ✅
Every answers here solved my problem. The first answer here was Ofek's answer. It works well, what i need to do to achieve the result i want is only to change the "<span>" + input + "</span>" inside the replace() function into :
"<span id='content-input' class='al question mb-0'>" + input + "</span>" to make the span element has the CSS Style like my screenshot above.
Other two answers, sid's answer and Rahul Kumar's answer also works well. But i prefer to choose Rahul Kumar's answer for its simplicity.
Thanks in advance to everyone that answered my questions!
Use regex to match the pattern and pass it to String.replace() method to replace the matched pattern in your string with new string <span>$1</span>. Here $1 indicates the captured group which is a content inside brackets *[...]*.
str = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
const regex = /\*\[(.*?)\]\*/g;
const finalStr = str.replace(regex, "<span>$1</span>");
console.log(finalStr);
You can use this method:
function replaceWithInput(str, replacer) {
var arr = str.split("*[");
for (var i = 1; i < arr.length; i++) {
var index = arr[i].indexOf("]*");
arr[i] = replacer(arr[i].slice(0, index)) + arr[i].slice(index + 2);
}
return arr.join("");
}
you use it like so:
function replace(input) {
return "<span>" + input + "</span>"
}
replaceWithInput("<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>", replace);
Using Regex you could do,
let c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>";
let newC = c.replace(/\*([[])/g, '<span>');
let newC2 = newC.replace(/\]([*])/g, '</span>');
console.log(newC2);

trim a string path using javascript

I have the following string:
var fileName = $(this).val();
this will give me a result:
C:\fakepath\audio_recording_47.wav
what I want is to obtain : audio_recording_47.wav
so, I need to trim it but I don't know how using javascript
please help
filename.split('\\').reverse()[0];
This will split the path by slashes, to obtain each part. Then to keep it simple, i reverse the array, so the last part that you need is now the first; and get the first part.
Or, even more simply: filename.split('\\').pop(), which will get the last item from the array.
You could write a little function to return the base name of the path:
function basename(fn) {
var x = fn.lastIndexOf("\\");
if (x >= 0) return fn.substr(x + 1);
return fn;
}
var filename = basename($(this).val());
You can do like this:
var fileName = $(this).val();
var path = fileName.split('\\');
var lastValue = path[path.length-1];
console.log(lastValue);//audio_recording_47.wav
Or, the shorter way you can do like this:
var fileName = $(this).val();
var path = fileName.split('\\').slice(-1);//audio_recording_47.wav
This should do it:
var trimmedFileName = fileName.match(/[^\\]*$/);
It matches everything that isn't a \ until the end of the string.
You could use a regular expression, like this:
var fileName = this.value.replace(/(?:[^\\\/]*[\\\/])*/, '');
Also, there is no need to use that snippet of jQuery, as this.value is both faster and simpler.

How to parse a url using Javascript and Regular Expression?

I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.

split string and leave the separators intact

I cannot find a good way to split a string using a separator string but leave the separator as the prefix of each element of the resulting array:
from
var s = 'blah0__blah1__blah2';
I need to get
['blah0', '__blah1', '__blah2']
the closest thing that I could get was
s.split(/(__)/);
which returns
['blah0', '__', 'blah1', '__', 'blah2']
but this I would need to traverse to merge the underscores.
Is there a better way?
EDIT:
here is my best effort so far:
'blah__blah1__blah2'.split(/(__[^_]+)/)
// => ["blah", "__blah1", "", "__blah2", ""]
still, there are empty strings in the output...
How about this:
var s = 'blah0__blah__blah'
var s_split = s.match(/(__)?(.(?!__))+./g)
console.log(s_split)
I'm pretty sure it's much more costly (time and memory wise) than simply reiterating and joining after a regular split.
If you replace __ with your separator it should work fine for most cases.
A two-step process.
var s = 'blah0__blah1__blah2';
var blahs = s.split('__');
var scoreBlahs = blahs.map(preScore);
alert(scoreBlahs);
function preScore(b) {
var x;
var result = x.concat('__',b);
return result;
}
'blah0__blah1__blah2'.match(/^[^_]+|_+[^_]+/g);
["blah0", "__blah1", "__blah2"]
Seems to give you what you want. Though It may vary, if your input isn't exactly as you show it.
Just prepend the seperator after you seperate the string
var value = "a,b,c";
var splitter = value.split(",");
for(var i = 0; i < splitter.length; i++) {
alert("," + splitter[i]);
}
Since you know the separator - just add it again later on:
var s = 'blah0__blah1__blah2';
var sep = '__';
var arr = s.split(sep);
for (var i = 1; i < arr.length; i++) {
arr[i] = sep + arr[i];
}
console.log(arr);
You could insert a secondary separator, and split on that, leaving the original intact.
var s = 'blah0__blah1__blah2';
s = s.replace('_', '_$');
s.split('$');

javascript jQuery - Given a comma delimited list, how to determine if a value exists

given a list like:
1,3,412,51213,djdd#asdasd.net, blahblah, 123123123123
which lives inside of a input type"text" as a value:
<input type="text" value="1,3,412,51213,djdd#asdasd.net, blahblah, 123123123123, wow#wow.com" />
How can I determine if a value exists, like 3, or blahblah or wow#wow.com?
I tried spliting with inputval.split(',') but that only gives me arrays. Is search possible?
Like this:
if (jQuery.inArray(value, str.replace(/,\s+/g, ',').split(',')) >= 0) {
//Found it!
}
The replace call removes any spaces after commas.
inArray returns the index of the match.
Utilizing jQuery:
var exists = $.inArray(searchTerm, $('input').val().split(',')) != -1;
exists is now an boolean value indicating whether searchTerm was found in the values.
var list = inputval.split(',');
var found = false;
for (var i=0; i<list.length; ++i) {
if (list[i] == whateverValue) {
found = true;
break;
}
}
You can be extra picky about the value matching by using "===" if it must be of the same type. Otherwise, just use "==" since it will compare an int to a string in a way that you probably expect.
You'l want to use var arr = theString.split(',') and then use var pos = arr.indexOf('3');
http://www.tutorialspoint.com/javascript/array_indexof.htm
This'll do it:
var val = $('myinput').val()
val = ',' + val.replace(', ',',').replace(' ,',',').trim() + ','; // remove extra spaces and add commas
if (val.indexOf(',' + mySearchVal + ',' > -1) {
// do something here
}
And it makes sure start and end spaces are ignored too (I assume that's what you want).

Categories