I have a function where I get some values dynamically and I send them to other function.
function sample(){
//some code here
var latlong1=//some value;
var latlong2=//some value;
fnSplitString(latlong1,latlong2);
}
I am sending these values to a function say
function fnSplitString(l1,l2)
{
alert("Latlong1::::"+l1);
alert("LatLong2::::"+l2);
var splitStringLatLong=l1.split(",");
alert("split1"+splitStringLatLong[0]);
alert("split2"+splitStringLatLong[1]);
}
here my 'l1' and 'l2' are alerting the values properly as.
Latlong1::::lat=78.23456,long=26.56789
Latlong2::::lat=74.57585,long=22.67890
I want to extract only the numeric values from these two strings. Hence I tried splitting it first till comma. But the split is not working at all. I do not get any alert message. Where is the mistake? And how do I extract only numeric from the string?
There is an extra semi-colon at the end of the first line of your fnSplitString definition.
Try removing that and see if it works. Corrected code below.
function fnSplitString(l1,l2)
{
alert("Latlong1::::"+l1);
alert("LatLong2::::"+l2);
var splitStringLatLong=l1.split(",");
alert("split1"+splitStringLatLong[0]);
alert("split2"+splitStringLatLong[1]);
}
It's not the best solution but this works:
var temp = 'lat=78.23456,long=26.56789';
var lat = temp.substring(4, temp.indexOf(",long"));
var long = temp.substring(temp.indexOf("g")+2, temp.length);
alert(lat);
alert(long);
I think regex is the simplest solution.
I'm not very strong in this, but here goes:
var str = "lat=78.23456,long=26.56789";
var s = str.match(/(?:\d*\.)?\d+/g);
alert("string1: "+s[0]+", string2: "+s[1]);
The result is an array of strings, but you can convert it to whatever you want.
Related
I need to parse following shortcode, for example my shortcode is :
[shortcode one=this two=is three=myshortcode]
I want to get this, is and myshortcode and add to array so it will :
['this', 'is', 'myshortcode']
NOTE : I know generally shortcode parameter marked with " and " ( ie [shortcode one="this" two="is" three="myshortcode"] ), but I need to parse shortcode above without ""
Any help really appreciated
I'm assuming you want to parse the first string with Regex and output the three elements in order to add them to an array later. That seems rather simple, or am I misunderstanding what you need? I'm assuming the word shortcodeis as it will be in your string. You'd probably need two regex operations if you haven't located and isolated the shortcode string yet that you posted above:
/\[shortcode((?: \S+=\S+)+)\]/
Replacement: "$1"
If you already have the code exactly as you posted it, then you can skip the regex above. At any rate, you'll have end with the following regex:
/ \S+=(\S+)(?:$| )/g
You can then add all the matches to your array.
If this is is not what you're looking for, then perhaps a more real example of your code would help.
Here you go I have built a perfectly scalable solution for you. The solution works for any number of parameters.
function myFunction() {
var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]";
var output = new Array();
var res = str.split("=");
for (i = 1; i < res.length; i++) {
var temp = res[i].split(" ");
if(i == res.length-1){
temp[0] = temp[0].substring(0,temp[0].length-1);
}
output.push(temp[0]);
}
document.getElementById("demo").innerHTML = output;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);
You can try the above code.
Here's my solution: https://jsfiddle.net/t6rLv74u/
Firstly, remove the [shortcode and trailing ]
Next, split the result by space " "
After that, run through the array and remove anything that's on and before =, .*?=.
And now you have your result.
I have function that is supposed to "clean" a string and i'd like to use replace() to do that, but I can't figure out why the following code is not working when the text comes from an input[text].
for instance :
console.log(getCleanText("ééé")); // works fine, it displays : eee
but
// my_id is an input with type="text"
var my_text = document.getElementById("my_id").value
console.log(getCleanText(my_text)); // doesn't work at all, it displays : ééé
the function code is :
function getCleanText(some_text) {
var clean_text = some_text.toLowerCase();
clean_text = clean_text.replace("é", "e");
clean_text = clean_text.split("é").join("e"); // give it another try
return clean_text;
}
any idea ?
I'm willing to bet your problem lies in a misunderstanding of Unicode.
é
é
Those two characters above are two different characters. The first is the letter e, with an accent character (U+0301). The other is a single character, U+00E9.
You need to ensure you're replacing both versions.
I think the character "é" from element value is the different from the "é" constant. To resolve that you can take look at the int value of the input.
var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);
Then you will be able to detect what characters you are replacing.
If you want to just remove accents from text, take look at the question Remove accents/diacritics in a string in JavaScript
Try this:
function getCleanText(old_string)
{
var new_string = old_string.toLowerCase();
return new_string.replace(/é/g, 'e');
}
Ed: beaten by the Robert. For reference, see here: What are useful JavaScript methods that extends built-in objects?
Try this:
function cleanText(text) {
var re = new RegExp(/\u0301|\u00e9/g);
return text.replace(re, "e").toLowerCase();
}
cleanText("éééé")
--
Updated to use the proposed UniCode chars by Matt Grande
What is the output of
var my_text = document.getElementById("my_id").value; ?
Depending on your html, you might need to use other functions to get the data. e.g
var my_text = document.getElementById("my_id").innerHTML;
http://jsbin.com/obAmiPe/5/edit?html,js,console,output
I want to covert this string to jquery data table. I can't do this.
var str = "96,xxx,212,xxxx||
100,yyy,123,yyyy";
My original DataSet structure like this
var aDataSet = [['96','xxx','212','xxxx'],
['100','yyy','123','yyyy']];
This is my code what i tried;
var srchvalue = str.split('||');
for (var e = 0; e < srchvalue.length; e++) {
alert(srchvalue[e]);
aDataSet.push(srchvalue[e]);
}
But it's not convert the actual format.
You will just need to split() twice. You've done the first bit already. Then you will need to split the two strings in your array with the , as the separator.
You can use aDataSet.push(srchvalue[e].split(',')) inside the for loop you already have.
You are pushing in your array the result of a split on "||" which is a series of string like "96,xxx,212,xxxx". You need to split that string too in order to have a matrix:
[...]
aDataSet.push(srchvalue[e].split(','));
[...]
I got the solution, I used the below code to convert it.
var test = eval('[' + srchvalue[e].split(',') + ']');
aDataSet.push(test);
how to insert a string inside the url address after split ?
I have a simple code like this, but I just don't understand how split and join are work
I have tried "append" function but I can't get it right
I test and write it in
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_split
<html>
<body>
<script type="text/javascript">
var str="/image/picture.jpg";
var test = str.split("/");
for(var i = 0; i < test.length; i++) {
document.write(test[1].join('/original') + "<br />");
}
document.write(test);
</script>
</body>
the output that I want is simply like this :
"/image/original/picture.jpg"
note: thanks for the help.
Just use replace instead:
str.replace('image/', 'image/original/');
if you really want to convert it into an array for some reason:
var ary = str.split('/');
ary.splice(2, 0, 'original');
ary.join('/');
vikenoshi,
You want to use the Array.splice method to insert new elements into your resulting array that you created using String.split. The splice method is documented here:
http://www.w3schools.com/jsref/jsref_splice.asp
Here is the code which should do what you want:
function spliceTest() {
var url = "/image/picture.jpg";
// split out all elements of the path.
var splitResult = url.split("/");
// Add "original" at index 2.
splitResult.splice(2, 0, "original");
// Create the final URL by joining all of the elements of the array
// into a string.
var finalUrl = splitResult.join("/");
alert(finalUrl); // alerts "/image/original/picture.jpg"
};
I created a JsFiddle with a working example:
http://jsfiddle.net/S2Axt/3/
A note about the other methods I'm using:
join: Join creates a new string from an array. This string is constructed by transforming all of the elements of the array into a string, and appending or concatenating them together. You can optionally provide a delimitter. Here I use the / to split the portions of the path.
split: Split splits a string based on another string into an array.
You could also do this:
var wholeURL = "/image/picture.jpg";
var choppedUpURL = wholeURL.split("/");
var finalURL = "/" + choppedUpURL[1] + "/original/" + choppedUpURL[2];
alert(finalURL);
http://jsfiddle.net/jasongennaro/KLZUT/
It's quick and simple
var str="/image/picture.jpg";
var elems = str.split("/");
elems.splice(elems.length-1, 0, "original")
document.write(elems.join("/");
Note I'm using the splice method with a first argument of the length of the array - 1. This puts the string "original" in the second to last position in the final path, not matter how long the URL you pass in. If this isn't the desired behavior, you can change the code to read elems.splice(2, 0, "original"). This would put the string "original" in the second position in the path, no matter how long the URL is.
Part of the problem with your code is that you're calling join on a string, not an array, see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join.
The return type of split is an array, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split. So doing
var test = str.split("/");
means that test is an array. So then test[1] is a string of that array, and calling join on it won't work.
try:
var str="/image/picture.jpg";
var test = str.split("/");
test[3]=test[2];
test[2]='original';
document.write(test.join('/'));
If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.