Related
Ive a situation to remove some words from a delimitted string in which the last char is ¶.
That means that if the string is:
keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6
The output string should be:
keyword1,keyword2,keyword4,keyword6
How can we achieve that in javascript?
This is what i did but i would like to do it without looping:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.split(',');
var t=[];
$(s).each(function(index,element){
var lastchar=element[element.length-1];
if(lastchar!='¶')
{
t.push(element);
}
});
console.info(t.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Problem can be solved using regular expressions:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.replace(/,keyword\d+¶/g, '');
console.info(s);
You should use the filter functionality in the JS.
var _s = "keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6";
var _output = _s.split(",").filter(function(word){
return (word[word.length - 1] !== "¶");
}).join(",");
console.log(_output);
Regular expressions should work. They are likely slower than writing your own loops, but in most cases they are clearer and you won't notice the difference.
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
console.info('original: ' + s);
var edited = s.replace(/¶.+¶/, '');
console.info('result: ' + edited);
var s = 'keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var t = s.split(",").filter(function(word) {
return !word.slice(-1).match(/[\u{0080}-\u{FFFF}]/gu, "");
})
console.info(t);
You can use the filter! Obviously this checks for any character that isn't ASCII. You can simply check if the last character is your ¶.
This way:
var str ='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var keywords = str.split(",");
for(keyword in keywords){
if(keywords[keyword].includes("¶")){
keywords.splice(keyword,1);
}
}
console.log(keywords);
PS: Every method loops to do it, you just can't see it in some forms ^^
How can I somehow split/separate my JavaScript variable by comma (,).
And then check if value-of-any-of-the-separated-strings = "something"
For example, my variable has the value 1,2,3,4,5,6,7,8,9,10,2212312, and I want to check if any of the numbers are = 7 in a IF-Statement.
Does anyone have any ideas how this can be done?
First, split the string by ",". Then, use indexOf on the split-string array to see if the target string is found (-1 means it wasn't found in the array). For example:
var str = "1,2,3,4,5,6,7,8,9,10,10,2212312";
var split_str = str.split(",");
if (split_str.indexOf("7") !== -1) {
// Original string contains 7
}
References:
String.prototype.split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
Array.prototype.indexOf - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
This is a simple application of Array.prototype.some:
var yourVar = '1,2,3,4,5,6,7,8,9,10,2212312';
function isSeven(val) {
return val === '7';
}
if (yourVar.split(',').some(isSeven)) {
//do stuff
}
Another common way this could be written is:
if (~yourVar.split(',').indexOf('7')) {
//do stuff
}
Or if Array.prototype.contains has been defined:
if (yourVar.split(',').contains('7')) {
//do stuff
}
Or if you want to use a regular expression:
if (/(?:^|,)7(?:,|$)/.test(yourVar)) {
//do stuff
}
Note: Array.prototype.some, Array.prototype.indexOf and Array.prototype.contains all require polyfills to work correctly cross browser.
Split it into an Array, then use indexOf to see if it's there. If it returns -1, it isn't.
"1,2,3,4,5,6,7,8,9,10,2212312".split(",").indexOf("7")
man i hope it will help you.
var yourValues = '1,2,3,4,5,6,7,8,9,10,2212312';
var array = yourValues.split(",");
boolean isValue = false;
for(i in array)
{
if(array[i]=='7')
{
isValue=true;
}
}
if(isValue)
alert("your number is in the string");
else
alert("your number is in the string");
You could use Array.filter, something like:
var values = '1,2,3,4,5,6,7,8,9,10,2212312'.split(','), find = 7;
if ( values.filter(function(a){return +a === find;}).length ) { /* ... */ }
Use split and Array.indexOf()
var str = "1,2,3,4,5,6,7,8,9,10,2212312";
var num = 7;
var pieces = str.split(",");
var index = pieces.indexOf(num.toString());
It can be done with regular expressions too
var str = "1,2,3,4,5,6,7,8,9,10,2212312";
var num = 7;
var re = new RegExp("(^|,)" + num + "($|,)");
alert(re.test(str));
jsFiddle example
use split along with indexOf:
var someString = '1,2,3,4,5,6,7,8,9,10,2212312';
var splitArray = someString.split(',');
var sevenPosition = splitArray.indexOf('7');
http://jsfiddle.net/jbabey/f4NLY/
Are you looking for the "contains" function. You can use jQuery for this.
if ($.inArray(7, value-of-any-of-the-seperated-strings))
{
console.log("there is a 7!")
}
Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.
I have somewhat of an odd situation, where I need to fix a bug in a website where, when a string is created (dynamically) it adds 5 spaces before the string and 5 spaces after the string. Obviously, the best thing to do would be to fix the back end code and get rid of those spaces... long story short, I can't and I have to do it with javascript. I'm not quite sure how to do it, but this is what I was thinking
<!--Dynamically generated string including spaces added in backend-->
<span id="balance"> 245.34 </span>
My idea was to do the following with javascript
function removespace()
{
var oldString = document.getElementById('balance');
var newString = (THIS IS WHERE I AM STUCK... I NEED TO REMOVE THE SPACES);
document.getElementByID('balance').innerHTML = newString;
}
Does anyone have any suggestions?
Thanks!
ALSO FORGOT TO MENTION: I can't use any javascript libraries like prototype or jquery.
Edit: I have this so far... but it doesn't seem to be working:
<span id="balance"> $245.00 </span>
<script>
function removespace()
{
var oldString = document.getElementById('balance');
var newString = oldString.trim ();
document.getElementByID('balance').innerHTML = newString;
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
here is the solution I used... I finished it before I saw the other updates... but everyone was very helpful
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var oldString = document.getElementById('balance').innerHTML;
var newString = trim(oldString);
document.getElementById('balance').innerHTML = newString;
Unfortunetly JavaScript does not have a trim() function. But you can roll your own:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
and then do:
var newString = oldString.trim ();
the above function is from this website (first result on google for "javascript trim")
edit (based on your update to your question and comments):
change
var oldString = document.getElementById('balance');
to
var oldString = document.getElementById('balance').innerHTML;
and change
document.getElementByID('balance').innerHTML = newString;
to
document.getElementById('balance').innerHTML = newString; // notice the lower case d
and you have to call the removespace function at some point (but I'm sure you already do that) :)
Writting out of my head here.
var elem = doc.getElementById('balance');
var oldString = elem.innerHTML;
elem.innerHTML=oldString.(/^\s+|\s+$/g,"")
Something like that?
Edit: yep, only my first space is deleted, so I stole the whitespace from the answer number 1 :)
You try something like this
str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
use trim() to remove all white spaces
var newString = oldString.trim();
or use replace to replace white spaces with empty string:
var newString = oldString.replace(" ","");
with jQuery it's simple:
var newStr = jQuery.trim(oldStr);
If balance is meant to be a double you could convert it to a string:
var c = '1234';
d = c * 1;
then back to a string if need be by:
d = c.toString();
I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.
Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.
Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535