Find multiple fragments of string in a string - javascript

I have a string of IDs in CSV format in an input box
12,23,26,32
I have to check if this string contains 23 or 24, if yes then return false, else return true

Use indexOf. You can check if it contains a subString. If not found, it returns -1
var str = "12,23,26,32"
return !(str.indexOf("23")!=-1 || str.indexOf("24")!=-1) // Dont have 23 or 24
=======EDIT=======
Like #Matt said in comment, this solution will work also to "12,239,26,32" and thats not the point.
Make the split before check the indexOf, then you will get the element between the commas.
var array = "12,23,26,32".split(",");
return !(array.indexOf("23")!=-1 || array.indexOf("24")!=-1) // Dont have 23 or 24

!/(^|,)2[34](,|$)/.test( str );
or if there may be whitespace present
!/(^|,)\s*2[34]\s*(,|$)/.test( str );
The RegExp test method returns true if the string argument matches the regular expression or false if it doesn't. The ! inverts the result of the test call.
^ is the metacharacter for the start of the string, so(^|,) means either 'at the start of the string' or 'one comma character'.
It can't be written [^,] as that would mean 'one character that isn't a comma', and it can't be written [,^] as that means 'one character that is either a comma or a literal ^ character.
2[34] means 2 followed by 3 or 4.
(,|$) means a comma or the end $ of the string.
\s* means zero or more space characters.

if (/(?:^|,)(23|24)(?:,|$)/.test("12,23,26,32")) {
/* found 23 or 24 */
}

Try this
var str = "12,23,26,32";
var isFound = (str.indexOf('23') || str.indexOf('24')) > -1;

var str = "12,23,26,32";
var obj = str.split(",");
var isFound = false;
for(i=0; i < obj.length; i++)
{
if(obj[i] == "23" || obj[i] == "24")
{
isFound = true;
break;
}
}
return isFound;

Related

Regular expression match in javascript on a list of items

How to check in javascript if my string contains any of the characters ~ and ’.
Is there a way to achieve this using regular expression match test, rather than writing a for loop to check if my string contains any of there characters using indexOf()
regex.test(str); is the thing you want to check. It looks in str if it is mathing regex, true if it does, else false
var a = "hey";
var b = "h~y";
var c = "he’";
var reg = /[’~]/ ;
console.log(reg.test(a)); // false
console.log(reg.test(b)); // true
console.log(reg.test(c)) // true
Just try to find given string using indexOf() it will return value greater than -1. If value is 0,1 or any number then true else false.
var string = "Some Text'";
if (string.indexOf("~") > -1 || string.indexOf("'") > -1)
{
console.log("contains");
}else{
console.log("not contains");
}

Remove Any Non-Digit And Check if Formatted as Valid Number

I'm trying to figure out a regex pattern that allows a string but removes anything that is not a digit, a ., or a leading -.
I am looking for the simplest way of removing any non "number" variables from a string. This solution doesn't have to be regex.
This means that it should turn
1.203.00 -> 1.20300
-1.203.00 -> -1.20300
-1.-1 -> -1.1
.1 -> .1
3.h3 -> 3.3
4h.34 -> 4.34
44 -> 44
4h -> 4
The rule would be that the first period is a decimal point, and every following one should be removed. There should only be one minus sign in the string and it should be at the front.
I was thinking there should be a regex for it, but I just can't wrap my head around it. Most regex solutions I have figured out allow the second decimal point to remain in place.
You can use this replace approach:
In the first replace we are removing all non-digit and non-DOT characters. Only exception is first hyphen that we negative using a lookahead.
In the second replace with a callback we are removing all the DOT after first DOT.
Code & Demo:
var nums = ['..1', '1..1', '1.203.00', '-1.203.00', '-1.-1', '.1', '3.h3',
'4h.34', '4.34', '44', '4h'
]
document.writeln("<pre>")
for (i = 0; i < nums.length; i++)
document.writeln(nums[i] + " => " + nums[i].replace(/(?!^-)[^\d.]+/g, "").
replace(/^(-?\d*\.\d*)([\d.]+)$/,
function($0, $1, $2) {
return $1 + $2.replace(/[.]+/g, '');
}))
document.writeln("</pre>")
A non-regex solution, implementing a trivial single-pass parser.
Uses ES5 Array features because I like them, but will work just as well with a for-loop.
function generousParse(input) {
var sign = false, point = false;
return input.split('').filter(function(char) {
if (char.match(/[0-9]/)) {
return sign = true;
}
else if (!sign && char === '-') {
return sign = true;
}
else if (!point && char === '.') {
return point = sign = true;
}
else {
return false;
}
}).join('');
}
var inputs = ['1.203.00', '-1.203.00', '-1.-1', '.1', '3.h3', '4h.34', '4.34', '4h.-34', '44', '4h', '.-1', '1..1'];
console.log(inputs.map(generousParse));
Yes, it's longer than multiple regex replaces, but it's much easier to understand and see that it's correct.
I can do it with a regex search-and-replace. num is the string passed in.
num.replace(/[^\d\-\.]/g, '').replace(/(.)-/g, '$1').replace(/\.(\d*\.)*/, function(s) {
return '.' + s.replace(/\./g, '');
});
OK weak attempt but seems fine..
var r = /^-?\.?\d+\.?|(?=[a-z]).*|\d+/g,
str = "1.203.00\n-1.203.00\n-1.-1\n.1\n3.h3\n4h.34\n44\n4h"
sar = str.split("\n").map(s=> s.match(r).join("").replace(/[a-z]/,""));
console.log(sar);

traverse a string char by char javascript

function SimpleSymbols(str) {
var letter =['a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var newstr = "";
for (var i = 0; i<str.length; i++){
if (str.charAt(i).toLowerCase() in letter){
newstr += "M";
}
else{
newstr += "X";
}
}
return newstr;
}
If str is "Argument goes here" it returns XXXXXXXXX. WHy doesn't it return MMMMMMMMMM?
you do not look up an entry in an array with in. use indexOf() to find the position of an array entry. indexOf() will return the position or -1 if no entry is found.
for (var i = 0; i<str.length; i++){
var strChar = str.charAt(i).toLowerCase();
if ( letter.indexOf(strChar) >= 0 ) {
newstr += "M";
}
…
The in operator returns true if the object has a property with that name, not with that value.
An array is basically an object with numeric properties. I.e. the indexes are the property names of the object. It basically looks like this:
var letters = {
0: 'a',
1: 'b',
...
length: ...
};
So in your case the condition will only be true if str.charAt(i).toLowerCase() returns a number between 0 and letter.length (and since charAt only returns one character, it can only be 0-9).
Example:
> var letters = ['a', 'b', 'c'];
> 'a' in letters // array doesn't have a property 'a'
false
> 0 in letters // array has a property 0 (it's the first element)
true
So since, "Argument goes here" doesn't contain any digits, the in condition will always be false and that's why you get XXXXXX... as result.
See the question "How do I check if an array includes an object in JavaScript?" for testing the existence of an element in an array.
FWIW, to make the in operator work, you would have to create an object of the form:
var letters = {
'a': true,
'b': true,
// ...
};
but that's a bit cumbersome to write.
Allow me to offer a side view, another way handle what I think you intent to do by using Regular Expressions with something like:
"test2".replace(/[a-z]/gi,"M").replace(/[^M]/g,"X") //Outputs "MMMMX"
String.replace will replace an string that contains letters from [a-z] the i at the end of the expression means case insensitive. g means will search for all possible matches and not just the first match. In the second expression [^M] this ^ means negation so anything that is not an M will be replaced with X.
There is another way in which we implement a custom function within the String.replace using Regular Expressions and it can be implemented like this:
"test2".replace(/([a-z])|([^a-z])/gi,
function(m,g1, g2){
return g1 ? "M" : "X";
});
In regular expression parenthesis creates groups and | means or in this expression ([a-z])|([^a-z]) there 2 groups one with letters from a-z and the other which means everything that is not a-z with the replace function we asked only for group g1 if it is group 1 is M otherwise is an X.
Another cool thing you could do is add this function to all your string by prototyping it like:
String.prototype.traverse = function(){ return this.replace(/([a-z])|([^a-z])/gi,function(m,g1){ return g1 ? "M" : "X" });}
Then it can be used as simple as: "test1".traverse();

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

Get everything after the dash in a string in JavaScript

What would be the cleanest way of doing this that would work in both IE and Firefox?
My string looks like this sometext-20202
Now the sometext and the integer after the dash can be of varying length.
Should I just use substring and index of or are there other ways?
How I would do this:
// function you can use:
function getSecondPart(str) {
return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
A solution I prefer would be:
const str = 'sometext-20202';
const slug = str.split('-').pop();
Where slug would be your result
var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);
var the_string = "sometext-20202";
var parts = the_string.split('-', 2);
// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'
var the_text = parts[0];
var the_num = parts[1];
With built-in javascript replace() function and using of regex (/(.*)-/), you can replace the substring before the dash character with empty string (""):
"sometext-20202".replace(/(.*)-/,""); // result --> "20202"
AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).
Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.
myString.split('-').splice(1).join('-')
I came to this question because I needed what OP was asking but more than what other answers offered (they're technically correct, but too minimal for my purposes). I've made my own solution; maybe it'll help someone else.
Let's say your string is 'Version 12.34.56'. If you use '.' to split, the other answers will tend to give you '56', when maybe what you actually want is '.34.56' (i.e. everything from the first occurrence instead of the last, but OP's specific case just so happened to only have one occurrence). Perhaps you might even want 'Version 12'.
I've also written this to handle certain failures (like if null gets passed or an empty string, etc.). In those cases, the following function will return false.
Use
splitAtSearch('Version 12.34.56', '.') // Returns ['Version 12', '.34.56']
Function
/**
* Splits string based on first result in search
* #param {string} string - String to split
* #param {string} search - Characters to split at
* #return {array|false} - Strings, split at search
* False on blank string or invalid type
*/
function splitAtSearch( string, search ) {
let isValid = string !== '' // Disallow Empty
&& typeof string === 'string' // Allow strings
|| typeof string === 'number' // Allow numbers
if (!isValid) { return false } // Failed
else { string += '' } // Ensure string type
// Search
let searchIndex = string.indexOf(search)
let isBlank = (''+search) === ''
let isFound = searchIndex !== -1
let noSplit = searchIndex === 0
let parts = []
// Remains whole
if (!isFound || noSplit || isBlank) {
parts[0] = string
}
// Requires splitting
else {
parts[0] = string.substring(0, searchIndex)
parts[1] = string.substring(searchIndex)
}
return parts
}
Examples
splitAtSearch('') // false
splitAtSearch(true) // false
splitAtSearch(false) // false
splitAtSearch(null) // false
splitAtSearch(undefined) // false
splitAtSearch(NaN) // ['NaN']
splitAtSearch('foobar', 'ba') // ['foo', 'bar']
splitAtSearch('foobar', '') // ['foobar']
splitAtSearch('foobar', 'z') // ['foobar']
splitAtSearch('foobar', 'foo') // ['foobar'] not ['', 'foobar']
splitAtSearch('blah bleh bluh', 'bl') // ['blah bleh bluh']
splitAtSearch('blah bleh bluh', 'ble') // ['blah ', 'bleh bluh']
splitAtSearch('$10.99', '.') // ['$10', '.99']
splitAtSearch(3.14159, '.') // ['3', '.14159']
For those trying to get everything after the first occurrence:
Something like "Nic K Cage" to "K Cage".
You can use slice to get everything from a certain character. In this case from the first space:
const delim = " "
const name = "Nic K Cage"
const result = name.split(delim).slice(1).join(delim) // prints: "K Cage"
Or if OP's string had two hyphens:
const text = "sometext-20202-03"
// Option 1
const opt1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const opt2 = text.split('-').slice(1).join("-") // prints: 20202-03
Efficient, compact and works in the general case:
s='sometext-20202'
s.slice(s.lastIndexOf('-')+1)
Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.
You can use split method for it. And if you should take string from specific pattern you can use split with req. exp.:
var string = "sometext-20202";
console.log(string.split(/-(.*)/)[1])
Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.
Just a loop and two ifs.
function getAfterDash(str) {
var dashed = false;
var result = "";
for (var i = 0, len = str.length; i < len; i++) {
if (dashed) {
result = result + str[i];
}
if (str[i] === '-') {
dashed = true;
}
}
return result;
};
console.log(getAfterDash("adfjkl-o812347"));
My solution is performant and handles edge cases.
The point of the above code was to procrastinate work, please don't actually use it.
To use any delimiter and get first or second part
//To divide string using deimeter - here #
//str: full string that is to be splitted
//delimeter: like '-'
//part number: 0 - for string befor delimiter , 1 - string after delimiter
getPartString(str, delimter, partNumber) {
return str.split(delimter)[partNumber];
}

Categories

Resources