JavaScript if string is in comma delimited string - javascript

I have string like this: str = "ball, apple, mouse, kindle";
and I have another text to search in this string: search = 'apple';
How to determine using JavaScript if apple exist in comma delimited string?
P.S: str can be with or without spaces between comma and next item.

Simple solution:
var str = "ball, apple, mouse, kindle";
var hasApple = str.indexOf('apple') != -1;
However, that will also match if str contains "apple fritters":
var str = "ball, apple fritters, mouse, kindle";
var hasApple = str.indexOf('apple') != -1; // true
There are different approaches you could do to get more specific. One would be to split the string on commas and then iterate through all of the parts:
var splitString = str.split(',');
var appleFound;
for (var i = 0; i < splitString.length; i++) {
var stringPart = splitString[i];
if (stringPart != 'apple') continue;
appleFound = true;
break;
}
NOTE: You could simplify that code by using the built-in "some" method, but that's only available in newer browsers. You could also use the Underscore library which provides its own "some" method that will work in any browser.
Alternatively you could use a regular expression to match "apple" specifically:
var appleFound = /\Wapple,/.test(',' + str + ',');
However, I think your real best bet is to not try and solve this yourself. Whenever you have a problem like this that is very common your best bet is to leverage an existing library. One example would be the Underscore String library, especially if you're already using Underscore. If not, there are other general purpose string utility (eg. String.js) libraries out there you can use instead.

To really test whether the exact character sequence "apple" is an item in your comma separated list (and not just a substring of the whole string), you can do (considering optional spaces before and after the value):
If Array#indexOf is available:
var items = str.split(/\s*,\s*/);
var isContained = items.indexOf('apple') > -1;
If Array#some is available:
var items = str.split(/\s*,\s*/);
var isContained = items.some(function(v) { return v === 'apple'; });
With a regular expression:
var isContained = /(^|,)\s*apple\s*($|,)/.test(str);

you can turn the string in to an array and check the search string is in it.
var stuffArray = str.split(",");
var SearchIndex = stuffArray.indexOf("Apple");
the search SearchIndex represent the position in the array.
if the SearchIndex < 0 the item is not found.

You can use String.split() and Array.indexOf().
var str = "ball, apple, mouse, kindle";
var search = "apple";
var arr = str.split(", ");
if (arr.indexOf(search) !== -1) {
alert('yes');
} else {
alert('no');
}

There are some great answers here arleady, but I thought I'd give an alternative using regex's. This will be case insensitive, so will match 'Apple' or 'apple'. Also, it will not match "Appleby's" or "apple pie", so you'll be spared false positives (or the regex can be changed to include those):
var str = "ball, apple, mouse, kindle";
var whatToFind = "apple";
var myRegEx = new RegExp(",\\s*" + whatToFind + "\\s*,", "i");
myRegEx.test(str);
That was the basic regex. Here it is inside a function and with some tests:
var str = "ball, apple, mouse, kindle";
var str2 = "ball, apple pie, house,cat";
var str3 = "ball,Apple,house, cat";
var str4 = "ball,Appleby's, peach, dog";
strs = [str, str2, str3, str4];
var searchFor = "apple";
var matches = function (stringToSearch, whatToFind)
{
var myRegEx = new RegExp(",\\s*" + whatToFind + "\\s*,", "i");
return myRegEx.test(stringToSearch);
}
strs.forEach(function (st) {
var confirm = " was ";
if(matches(st, searchFor)==true)
confirm = " was ";
else
confirm = " was not ";
console.log( '"' + searchFor + '"' + confirm + "found in " + '"' + st + '"');
});
Here is the output:
"apple" was found in "ball, apple, mouse, kindle"
"apple" was not found in "ball, apple pie, house,cat"
"apple" was found in "ball,Apple,house, cat"
"apple" was not found in "ball,Appleby's, peach, dog"

You can do this the very easy, yet error prone way of checking the index of the string apple in your comma separated list:
var str = "ball, apple, mouse, kindle"
var index = str.indexOf('apple')
alert(index)
Checking the result is >-1 tells you that the str contains the string apple. However, this will give you false positives where for example str is:
var str = "ball, crab apple, mouse, kindle"
That will still give you an index for apple that is >-1 - probably not what you want.

please note, for this code, you need jquery library
str = "ball, apple, mouse, kindle";
str_arr = str.split(',');
for (i = 0; i < str_arr.length; i++) {
if($.trim(str_arr[i]) === "apple"){
alert('yiha i found an apple here. here it is: ' + str_arr[i]);
}
}

Here's another solution using regular expressions
//some test csv
var t = '1,2,3,4,32,apple,apple struddle,applestruddle,41,42,43';
now create a regular expression 'reg' here .. it can be done hardcoded like
var reg = /(^|,\s{0,1})\bapple struddle\b(,|$)/;
or programmatically like
var check_value = "apple";
var reg = new RegExp("(^|,\\s{0,1})\\b" + check_value + "\\b(,|$)","g");
and you can simply call
if(reg.test(t)){
console.log("apple .. no struddle!!");
}
Just a note on the reg exp .. I put in a \s{0,1} after the comma just to cater for a ", " vs a "," seperator.. obviously .. sort out your spacing requirements to suite yourself ;)

I've not been tested the performance, but I think using the array of separated values must be one of the short and straight solutions. So I suggest to get an array of values and check with inArray command like below:
var str = "ball,apple,mouse,kindle";
var search = 'apple';
var strArray = str.split(',');
if ($.inArray(search, strArray) !== -1) {
alert('hurrah :)');
}
else {
alert('nothing!');
};

Related

regex (only 1 dot)

I have a regEx where I replace everything whats not a number:
this.value.replace(/[^0-9\.]/g,'');
how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)
(I know you can use input just number (thats not an option in this project for me))
You can use a simple trick of:
splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi
Here is an example code:
// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
Proof-of-concept example:
var tests = [
'xx99',
'99xx',
'xx99xx',
'xxxx999.99.9xxx',
'xxxx 999.99.9 xxx',
'xx99xx.xx99xx.x9',
'xx99xx.99x.9x',
'xx99.xx99.9xx'
];
for (var i = 0; i < tests.length; i++) {
var str = tests[i];
// Split and rejoin, keeping only first occurence of `.`
var splitStr = str.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}
I resolved it with.
this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");

How can I replace single digit numbers within a string without affecting 2 digit numbers in that string

I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>

Replace a string word with empty space with js

I have the following string:
var string = "Deluxe 3 Bed Private"
and the following code to replace the "Private" word with an empty space:
var rooms = ["Basic", "Standard", "Superior", "Deluxe", "Private"];
//var room = "room";
vwo_$(document).ready(function(){
WRI.eventBus.on('ui:microsite:availabilityStore:refresh', function(){
var roomName = $(".roomnamelink");
roomName.each(function(){
for (var i = 0; i < rooms.length; i++) {
var pattern = "[^\s]" + rooms[i];
var regex = new RegExp(pattern);
string = string .replace(regex, " ");
}
});
})
but my regex is probably wrong.
If the word "Private" is found in the string I want that replaced with an empty space.
var string = "Deluxe 3 Bed"
I want to replace any of the words found in the rooms array with an empty space
you can use one regex for all the possible words
var regex = /\b(Basic|Standard|Superior|Deluxe|Private)\b/gi
and the use it with String#replace method
var string = "Deluxe 3 Bed Private"
string.replace(regex, '')
You could search for white space and the word, you want to replace.
var re = /[\s]*?private/gi,
str = 'Deluxe 3 Bed Private',
subst = '';
var result = str.replace(re, subst);
console.log('#' + result + '#');
you can do it by using very simple code like below:
var string = "Deluxe 3 Bed Private"
//checking whether private is in String or not.
if (wordInString(string, 'Private'))
{
string = string.replace('Private', ' ');
}
alert(string);
function wordInString(s, word) {
return new RegExp('\\b' + word + '\\b', 'i').test(s);
}
that's all.. :)

How to cut third symbol from string and alert it without third symbol

How can i correctly cut out letter "v" and alert str without "v"
var str = "Javascript";
var cut = str.substring(2,3);
var str = "Javascript";
var cut = str.substring(0,2) + str.substring(3);
alert(cut);
You're using the right tool (String#substring). You need two substrings that you put back together, the "Ja" and the "ascript". So:
var str = "Javascript";
var cut = str.substring(0, 2) + str.substring(3);
alert(cut);
Another option would be String#replace, which will replace the first occurrence of what you give it unless you tell it to do it globally with a regex and the g flag (which we won't, because we just want to remove that one v):
var str = "Javascript";
var cut = str.replace("v", "");
alert(cut);
Just for fun, there is another way, but it's a bit silly: You can split the string into an array of single-character strings, remove the third entry from the array, and then join it back together:
var str = "Javascript";
var cut = str.split("").filter(function(_, index) {
return index != 2;
}).join("");
alert(cut);
or
var str = "Javascript";
var cut = str.split("");
cut.splice(2, 1); // Delete 1 entry at index 2
cut = cut.join("");
alert(cut);
...but again, that's a bit silly. :-)
use replace method
var str = "Javascript";
str = str.replace("v", "");
alert(str);

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Categories