Related
I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)
I want to find and replace a part of string if present in string.
String is like '1.png,2.png,3.jpg,4.gif'
I want find 1.png in this string and then replace it if exist with 1.jpg.
I am not able to find it using search() and indexOf() method.
and since i am not able to find it i cannot replace it.
I am trying this way
var str = '1.png'
var new_str = '1.jpg'
var main_str = '1.png,2.png,3.jpg,4.gif';
if(main_str.indexOf(str) > 0){
alert('found')
// now replace it with new_str
}
else{
alert('not found')
}
I have tried following combination but these are not working.
main_str.indexOf('str') > 0
main_str.indexOf(/\str/) > 0
main_str.indexOf(/\"str"/) > 0
main_str.indexOf(str) > 0
Please see and suggest any possible way to do this.
Thanks
The index of 1.png in your string is actually 0, that is why your condition fails. Correct way is to check whether index is not negative, since indexOf returns -1 if substring is not found:
if(main_str.indexOf(str) >= 0){
but even better approach here is to use replace:
main_str.replace(str, new_str)
Since the main_str contains 1.png at index 0, you can never find it with the check main_str.indexOf('str') > 0. Remeber that javascript returns -1 if not found and not zero. So you'll have to update your condition to:
main_str.indexOf('str') != -1
try,
var str="1.png,2.png,3.jpg,4.gif";
var newStr=str.replace(".png",".jpg");
you can use the replace method:
var str = '1.png,2.png,3.jpg,4.gif';
var result=str.replace('1.png','1.jpg')
You can do the replacement using replace :
main_str = main_str.replace(str, new_str)
If you want to replace more than one occurrence, use
main_str = main_str.replace(new RegExp(str,'g'), new_str)
If you want to alert before replacing, do this :
var r = new RegExp(str,'g');
if (main_str.match(r)) {
alert('found')
main_str = main_str.replace(r, new_str)
} else {
alert('not found')
}
you can do this:
var str = "1.png,2.png,3.jpg,4.gif";
var re = /(.png)/i;
var found = str.match(re);
//now ask the user or do whatever else is needed
if (found){
found = confirm("Really overwrite");
}
if (found){
str = str.replace(re, ".jpg");
}
I allow in the string now also upper case or mixed case, like ".Png" or ".PNG"
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!")
}
I have a string that and I am trying to extract the characters before the quote.
Example is extract the 14 from 14' - €14.99
I am using the follwing code to acheive this.
$menuItem.text().match(/[^']*/)[0]
My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.
What I am I doing wrong with the match?
This is the what you should use to split:
string.slice(0, string.indexOf("'"));
And then to handle your non existant value edge case:
function split(str) {
var i = str.indexOf("'");
if(i > 0)
return str.slice(0, i);
else
return "";
}
Demo on JsFiddle
Nobody seems to have presented what seems to me as the safest and most obvious option that covers each of the cases the OP asked about so I thought I'd offer this:
function getCharsBefore(str, chr) {
var index = str.indexOf(chr);
if (index != -1) {
return(str.substring(0, index));
}
return("");
}
try this
str.substring(0,str.indexOf("'"));
Here is an underscore mixin in coffescript
_.mixin
substrBefore : ->
[char, str] = arguments
return "" unless char?
fn = (s)-> s.substr(0,s.indexOf(char)+1)
return fn(str) if str?
fn
or if you prefer raw javascript : http://jsfiddle.net/snrobot/XsuQd/
You can use this to build a partial like:
var beforeQuote = _.substrBefore("'");
var hasQuote = beforeQuote("14' - €0.88"); // hasQuote = "14'"
var noQoute = beforeQuote("14 €0.88"); // noQuote = ""
Or just call it directly with your string
var beforeQuote = _.substrBefore("'", "14' - €0.88"); // beforeQuote = "14'"
I purposely chose to leave the search character in the results to match its complement mixin substrAfter (here is a demo: http://jsfiddle.net/snrobot/SEAZr/ ). The later mixin was written as a utility to parse url queries. In some cases I am just using location.search which returns a string with the leading ?.
I use "split":
let string = "one-two-three";
let um = string.split('-')[0];
let dois = string.split('-')[1];
let tres = string.split('-')[2];
document.write(tres) //three
Say, I have a string
"hello is it me you're looking for"
I want to cut part of this string out and return the new string, something like
s = string.cut(0,3);
s would now be equal to:
"lo is it me you're looking for"
EDIT: It may not be from 0 to 3. It could be from 5 to 7.
s = string.cut(5,7);
would return
"hellos it me you're looking for"
You're almost there. What you want is:
http://www.w3schools.com/jsref/jsref_substr.asp
So, in your example:
Var string = "hello is it me you're looking for";
s = string.substr(3);
As only providing a start (the first arg) takes from that index to the end of the string.
Update, how about something like:
function cut(str, cutStart, cutEnd){
return str.substr(0,cutStart) + str.substr(cutEnd+1);
}
Use
substring
function
Returns a subset of a string between
one index and another, or through the
end of the string.
substring(indexA, [indexB]);
indexA
An integer between 0 and one less than the length of the string.
indexB
(optional) An integer between 0 and the length of the string.
substring extracts characters from indexA up to but not including indexB. In particular:
* If indexA equals indexB, substring returns an empty string.
* If indexB is omitted, substring extracts characters to the end
of the string.
* If either argument is less than 0 or is NaN, it is treated as if
it were 0.
* If either argument is greater than stringName.length, it is treated as
if it were stringName.length.
If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).
Some other more modern alternatives are:
Split and join
function cutFromString(oldStr, fullStr) {
return fullStr.split(oldStr).join('');
}
cutFromString('there ', 'Hello there world!'); // "Hello world!"
Adapted from MDN example
String.replace(), which uses regex. This means it can be more flexible with case sensitivity.
function cutFromString(oldStrRegex, fullStr) {
return fullStr.replace(oldStrRegex, '');
}
cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
s = string.cut(5,7);
I'd prefer to do it as a separate function, but if you really want to be able to call it directly on a String from the prototype:
String.prototype.cut= function(i0, i1) {
return this.substring(0, i0)+this.substring(i1);
}
string.substring() is what you want.
Just as a reference for anyone looking for similar function, I have a String.prototype.bisect implementation that splits a string 3-ways using a regex/string delimiter and returns the before,delimiter-match and after parts of the string....
/*
Splits a string 3-ways along delimiter.
Delimiter can be a regex or a string.
Returns an array with [before,delimiter,after]
*/
String.prototype.bisect = function( delimiter){
var i,m,l=1;
if(typeof delimiter == 'string') i = this.indexOf(delimiter);
if(delimiter.exec){
m = this.match(delimiter);
i = m.index;
l = m[0].length
}
if(!i) i = this.length/2;
var res=[],temp;
if(temp = this.substring(0,i)) res.push(temp);
if(temp = this.substr(i,l)) res.push(temp);
if(temp = this.substring(i+l)) res.push(temp);
if(res.length == 3) return res;
return null;
};
/* though one could achieve similar and more optimal results for above with: */
"my string to split and get the before after splitting on and once".split(/and(.+)/,2)
// outputs => ["my string to split ", " get the before after splitting on and once"]
As stated here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split
If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.
You need to do something like the following:
var s = "I am a string";
var sSubstring = s.substring(2); // sSubstring now equals "am a string".
You have two options about how to go about it:
http://www.quirksmode.org/js/strings.html#substring
http://www.quirksmode.org/js/strings.html#substr
Try the following:
var str="hello is it me you're looking for";
document.write(str.substring(3)+"<br />");
You can check this link
this works well
function stringCutter(str,cutCount,caretPos){
let firstPart = str.substring(0,caretPos-cutCount);
let secondPart = str.substring(caretPos,str.length);
return firstPart + secondPart;
}