transfer special charcter to normal charcter - javascript

I am try to load city name from the XML file using javascript AJAX and finally success on them.
var region=Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar
This is my output; in this output some charcter are non standard US ASCII and I want to change into normal chars, like:
var region:- Ahmadabad,Surat,Vadodara,Rajkot,Bhavnagar,Jamnagar,Nadiad,Gandhinagar,Junagadh,Surendranagar
How can I do that?

This is a pure javascript solution though it is not optimal and might perform not well:
// create a character map to convert one char to another
var charMap = {
"ā" : "a",
"ū" : "u"
};
var region="Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar";
// split original string into char array
var chars = region.split('');
// init new array for conversion result
var charsConverted = [];
// convert characters one by one
for(var i = 0; i < chars.length; i++){
var char = chars[i];
// this will try to use a matching char from char map
// will use original if no pair found in charMap
charsConverted.push( charMap[char] || char);
}
// join array to string
var result = charsConverted.join('');
alert(region);
alert(result);
Again this is just an idea and might need a lot of tweaking.
Code in action: http://jsfiddle.net/L5Yzf/
HTH

Related

having an issue w/ .split in a JavaScript function that gets the max # of repeating chars per word in a string

I'm writing a JavaScript function that has to take in a string argument & determine the word or words with the maximum number or repeated (or most frequent) non sequential characters and return that word or words.
The way that I went about solving this problem was to first find the maximum number of times a character was repeated per word and record that number to use later in a function to test against every word in the string (or the array of strings as I later split it); if the word met the conditions, it's pushed into an array that I return.
My maxCount function seemed to work fine on its own but when I try to make it work together with my other function to get the words with max repeated chars returned, it's not working in JS Fiddle - it keeps telling me that "string.split is not a function" - I'll admit that the way I'm using it (string.split(string[i]).length) to analyze words in the string letter by letter is a bit unconventional - I hope there's some way to salvage some of my logic to make this work in the functions that can work together to get the results that I want.
Also, I don't know if I'm using Math.max correctly/in a "legal" way, I hope so. I've tried switching my variable name to "string" thinking that would make a difference but it did not even though my arguments are of the string variety and it's a string that's being represented.
Here's a link to my Fiddle:
https://jsfiddle.net/Tamara6666/rdwxqoh6/
Here's my code:
var maxCount = function (word) {
/// var maxRepeats = 0;
var numArray = [];
var string = word;
for (var i = 0, len = string.length; i < len; i++) {
//split the word('string') into letters at the index of i
numArray.push((string.split(string[i]).length) -1);
}
var max = Math.max(...numArray);
return max;
}
///console.log(maxCount("xxxxxxxxxxxxx"));
var LetterCount = function(string){
var repeatedChars = 0;
var wordArray=[];
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
var eachWord = stringArray[i];
var maxRepeats = maxCount(stringArray);
if (repeatedChars < maxRepeats) {
repeatedChars = maxRepeats;
wordArray = [eachWord];
}else if (repeatedChars == maxRepeats) {
wordArray.push(eachWord);
}
}
return wordArray;
};
console.log(LetterCount("I attribute my success to cats"));
//should return ["attribute", "success"]
*** I've tried to map this first function onto the array formed when I split my string at the spaces but it is just returned me an empty array (I also might not have been using map correctly in this example); I also have tried using valueOf to extract the primitive value out of the array from the first function which also didn't work. I'm not really sure what to do at this point or what angle to take- I feel if I understood more what was going wrong I could more easily go about fixing it. Any help would be much appreciated. Thanks!
You are passing an array to maxCount at line 20, while it expects a string:
var maxRepeats = maxCount(stringArray);
You should use:
var maxRepeats = maxCount(eachWord);
If you are getting split is not a function error then first make sure that your string isn't null by printing it on console. If it isn't null then confirm that its a string not an array or some other thing.

Javascript - best way to parse custom tags [duplicate]

This question already has answers here:
XML parsing of a variable string in JavaScript
(10 answers)
Closed 9 years ago.
I wrote an API that returns the following
<location><lat>41.47033705</lat><lon>-81.93612862</lon></location>
<location><lat>41.470320224762</lat><lon>-81.9364535808563</lon></location>
<location><lat>41.4704650640488</lat><lon>-81.9449239969254</lon></location>
<location><lat>41.4780235290527</lat><lon>-81.8454140424728</lon></location>
<location><lat>41.48597253</lat><lon>-81.82579113</lon></location>
I have an AJAX call that gets this and now I need to use it in my JavaScript.
Ultimately I would like and 2d Array [lat,lon]
What is the least amount of code to do this?
Assuming the response is valid XML, you can use getElementsByTagName and push to an array:
var arr = [];
for (var location in response.getElementsByTagName('location'))
{
arr.push([
parseFloat(location.getElementsByTagName('lat')[0]),
parseFloat(location.getElementsByTagName('lon')[0])
]);
}
You can make your AJAX call via XmlHttmlRequest and get responseXML. Then you can parse your data via XmlDocument method and properties.
You can even run Xpath queries on the result to select exactly what you need.
Just use JQuery's selector engine to parse your code.
Wrap your elements in a <div id="data"> ... </data> for easy selection and you can do the following:
var _locations = $('#data').find('location');
var my_data = [];
$.each(_locations, function(index, loc) {
var _lat = $(loc).find('lat');
var _lon = $(loc).find('lon');
my_data.push([_lat.text(), _lon.text()]);
})
// my_data will contain a 2D array of your lat, lon
GoodLuck
-Kiru
Regex 101 Demo
Regex
<lat>([^<]+)<\/lat><lon>([^<]+)<\/lon>
using g (global) flag
Description
<lat> Literal <lat>
1st Capturing group ([^<]+)
Negated char class [^<] 1 to infinite times [greedy] matches any character except:
< The character <
<\/lat><lon> Literal </lat><lon>
2nd Capturing group ([^<]+)
Negated char class [^<] 1 to infinite times [greedy] matches any character except:
< The character <
<\/lon> Literal </lon>
g modifier: global. All matches (don't return on first match)
Visualization
Taking the above to solve your specific issue
DEMO jsFiddle
JS
var text = " <location><lat>41.47033705</lat><lon>-81.93612862</lon></location><location><lat>41.470320224762</lat><lon>-81.9364535808563</lon></location><location><lat>41.4704650640488</lat><lon>-81.9449239969254</lon></location><location><lat>41.4780235290527</lat><lon>-81.8454140424728</lon></location><location><lat>41.48597253</lat><lon>-81.82579113</lon></location>";
var myregexp = /<lat>([^<]+)<\/lat><lon>([^<]+)<\/lon>/g;
var results = new Array();
var match = myregexp.exec(text);
while (match != null) {
var result = new Array();
for (var i = 1; i < match.length; i++) {
result.push(match[i]);
}
results.push(result);
match = myregexp.exec(text);
}
console.log(results);
the variable results contains a 2d array [lat, lon]

convert textareas string value to JavaScript array separated by new lines

I have a textarea where the user can write up to 1000 characters. I need to get the jQuery('#textarea').val() and create an array where each item is a line of the textarea's value. That means:
This is a nice line inside the textarea.
This is another line.
(let's asume this line is empty - it should be ignored).
Someone left more than 2 new lines above.
Should be converted to a JavaScript array:
var texts = [];
text[0] = 'This is a nice line inside the textarea.';
text[1] = 'This is another line.';
text[2] = 'Someone left more than 2 new lines above.';
That way they can be easily imploded for to querystring (this is the qs format required by the provider):
example.com/process.php?q=["This is a nice line inside the textarea.","This is another line.","Someone left more than 2 new lines above."]
I tried both the phpjs explode() and string.split("\n") approaches but they doesn't take care of the extra new lines (aka line breakes). Any ideas?
String.prototype.split() is sweet.
var lines = $('#mytextarea').val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
Note that String.prototype.split is not supported on all platforms, so jQuery provides $.split() instead. It simply trims whitespace around the ends of a string.
$.trim(" asd \n") // "asd"
Check it out here: http://jsfiddle.net/p9krF/1/
Use split function:
var arrayOfLines = $("#input").val().split("\n");
var split = $('#textarea').val().split('\n');
var lines = [];
for (var i = 0; i < split.length; i++)
if (split[i]) lines.push(split[i]);
return lines;
Try this
var lines = [];
$.each($('textarea').val().split(/\n/), function(i, line){
if(line && line.length){
lines.push(line);
}
});

splitting a string in js where a pattern DOES NOT match?

i am trying to split a TextArea value where a pattern does not match
the text is like following:
Some Good Tutorials
http://a.com/page1
http://a.com/page2
Some Good Images
http://i.com/p1
http://i.com/p2
Some Good Videos
http://m.com/p1
http://m.com/p2
now i want to get only the links from the text so a better solution would be to split the whole string in an array of strings where the a line is not a url and then from amongst this array split each string with "\n"
edit:
okay i found a solution, i can find lines which does not begin with http:// or https:// and replace them with a good place holder after than i can get the links
though i am weak in regex so can someone tell me how to do this in javascript?
Match the pattern. don't split with it.
value=value.match(/http\:\/\/.+/g)
(.+matches everything to the end of a line)
Solved finally! Here is the code:
function split_lines() {
var oText = $('linkTxtArea').value;
removeBlankLines(); // a helper function to remove blank lines
oText = oText.split("\n"); // first split the string into an array
for (i = 0; i < oText.length; i++) // loop over the array
{
if (!oText[i].match(/^http:/)) // check to see if the line does not begins with http:
{
oText[i] = oText[i].replace(oText[i], "!replaced!"); // replace it with '!replaced!'
}
}
oText = oText.toString().split("!replaced!"); // now join the array to a string and then split that string by '!replaced!'
for (i = 1; i < oText.length; i++)
{
oText[i] = oText[i].replace(/^,/,"").replace(/,$/,""); // there were some extra commas left so i fixed it
}
return oText;
}

JavaScript split function

i like to split a string depending on "," character using JavaScript
example
var mystring="1=name1,2=name2,3=name3";
need output like this
1=name1
2=name2
3=name3
var list = mystring.split(',');
Now you have an array with ['1=name1', '2=name2', '3=name3']
If you then want to output it all separated by spaces you can do:
var spaces = list.join("\n");
Of course, if that's really the ultimate goal, you could also just replace commas with spaces:
var spaces = mystring.replace(/,/g, "\n");
(Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)
Just use string.split() like this:
var mystring="1=name1,2=name2,3=name3";
var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
If you the want string version of result (unclear from your question), call .join() like this:
var newstring = arr.join(' '); //(though replace would do it this example)
Or loop though, etc:
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
You can play with it a bit here

Categories