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
Related
Suppose I have a list formed by words including special characters:
one
<two></two>
three#
$four
etc.
I want to find all words in the list that contain specific letters,
I've tried to use
var myList = "<one></one> $two three#";
var myRegex = /\bMYWORD[^\b]*?\b/gi;
alert(myList.match(myRegex));
But this does not work with special characters..
DEMO
Unfortunately I'm new to javascript, and I don't know what is the best way to create the list
and to separe the words in the list..
So based on your inputs, this does the trick:
var myList = "<one></one> $two three#";
var items = myList.split(' ');
$('#myInput').on('input',function(){
var matches = [];
for(var i = 0; i < items.length; i++) {
if(items[i].indexOf(this.value) > -1)
matches.push(items[i]);
}
$('#myDiv').text(matches.join(','));
});
Is this what you want?
If I understand correctly, all you need is to escape all special characters from your query string so that they are not considered as such by the RegEx engine. Something like this should work:
var myList = "<one></one> $two three#";
var query = "$two";
var myRegex = new RegEx(query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
alert(myList.match(myRegex));
Hat tip to the answer that provided the escaping mechanism.
Is this what you needed?
PD: I'd also recommend using console instead of alert.
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
I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>
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);
}
});
I'm taking some text and want to split it into an array. My goal is to be able to split it into phrases delimited by stopwords (words ignored by search engines, like 'a' 'the' etc), so that I can then search each individual phrase in my API. So for example: 'The cow's hat was really funny' would result in arr[0] = cow's hat and arr[1] = funny. I have an array of stopwords already but I can't really think of how to actually split by each/any of the words in it, without writing a very slow function to loop through each one.
Use split(). It takes a regular expression. The following is a simple example:
search_string.split(/\b(?:a|the|was|\s)+\b/i);
If you already have the array of stop words, you could use join() to build the regular expression. Try the following:
regex = new RegExp("\\b(?:" + stop_words.join('|') + "|\\s)+\\b", "i");
A working example http://jsfiddle.net/NEnR8/. NOTE: it may be best to replace these values than to split on them as there are empty array elements from this result.
This does a case insensitive .split() on your keywords, surrounded by word boundries.
var str = "The cow's hat was really funny";
var arr = str.split(/\ba\b|\bthe\b|\bwas\b/i);
You may end up with some empty items in the Array. To compact it, you could do this:
var len = arr.length;
while( len-- ) {
if( !arr[len] )
arr.splice( len, 1);
}
Quick and dirty way would be to replace the "stop word" strings with some unique characters (e.g. &&&), and then split based on that unique character.
For example.
var the_text = "..............",
stop_words = ['foo', 'bar', 'etc'],
unique_str = '&&&';
for (var i = 0; i < stop_words.length; i += 1) {
the_text.replace(stop_words[i], unique_str);
}
the_text.split(unique_str);