How to grab string(s) before the second " - "? - javascript

var string = "bs-00-xyz";
As soon as the second dash has detected, I want to grab whatever before that second dash, which is bs-00 in this case.
I am not sure what is the most efficient way to do that, and here is what I come up with.
JSFiddle = http://jsfiddle.net/bheng/tm3pr1h9/
HTML
<input id="searchbox" placeholder="Enter SKU or name to check availability " type="text" />
JS
$("#searchbox").keyup(function() {
var query = this.value;
var count = (query.match(/-/g) || []).length;
if( count == 2 ){
var results = query.split('-');
var new_results = results.join('-')
alert( "Value before the seond - is : " + new_results );
}
});

You could do it without regex with this
myString.split('-').splice(0, 2).join('-');

In case there are more than two dashes in your string...
var myString = string.substr(0, string.indexOf('-', string.indexOf('-') + 1));

Using a regular expression match:
var string = "bs-00-xyz";
newstring = string.match(/([^-]+-[^-]+)-/i);
// newstring = "bs-00"
This will work for strings with more than two dashes as well.
Example:
var string = "bs-00-xyz-asdf-asd";

I think splitting on character is a fine approach, but just for variety's sake...you could use a regular expression.
var match = yourString.match(/^([^\-]*\-[^\-]*)\-/);
That expression would return the string you're looking for as match[1] (or null if no such string could be found).

you need use lastIndexOf jsfiddle, check this example
link update...

Related

How to String include after character in nodejs, JavaScript

I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);

JavaScript regular expression for two-letter tokens separated by commas

I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.
Here i included the acceptable sting
string = ab,ca,ls,gz,tv......
I tried:
/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/
but it is not working as expected.
Try using /^[a-z]{2}(?:,[a-z]{2})*$/i instead (the | inside your pattern was problematic):
var string = 'ab,ca,ls,gz,tv'
var regex = /^[a-z]{2}(?:,[a-z]{2})*$/i
console.log(regex.test(string)) //=> true
If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:
(?:^|,)([a-zA-Z]{2})(?=,|$)
Live preview
var string = "ab,ca,ls,gz,tv";
const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;
match = regex.exec(string);
while (match != null) {
console.log(match[1]);
match = regex.exec(string);
}
The above outputs:
ab
ca
ls
gz
tv
Try this.
/^[a-z]{2}(,[a-z]{2})*$/i
var string1 = "ab,ca,ls,gz,tv"
var string2 = "ab,c,ls"
var string3 = "ab,ca"
var regex = /^[a-z]{2}(,[a-z]{2})*$/i
document.getElementById("test").innerHTML =
regex.test(string1) + "<br>" + // true
regex.test(string2) + "<br>" + // false
regex.test(string3) // true
<p id="test"></p>

Using Java Script or jquery regex to verify if a string contains another string

I am building a simple search where query string can have wild cards '*'. Search terms can be like following:
animal
ani*
*mal
an*al
all above should return true if the word is 'animal'.
how this can be done in JS / jquery?
will appreciate for help.
rnv
The match on a string is simple:
var mystring = "This is my string";
var myregex = /*some regex*/
var results = mystring.match(myregex); // you can also write the regex directly as the argument of the match method, without using any variable.
So in your case you could have:
var mystring = "animal";
var myregex = new RegExp(inputQuery.replace(/\*/g, '.*'), 'gi'); // gi stands for 'global' and 'ignorecase' when applying the regex
var results = mystring.match(myregex);
Beware that .* matches zero or more (comes from the * whildcard) character, ANY character (comes from the .)
If you want to match zero or more letter, number or underscoreuse \w*, if you want to match one or more, use \w+, and if you want to match a specific number of letters, use \w{x} (\w{3} matches exactly 3 letters).
var str = "anim*";
var replaced = str.replace("*", ".*");
var regex = new RegExp(replaced);
var result = regex.test("animal");
console.log(result);
change the str variable to get the result as true or false;
Implemented version - https://jsfiddle.net/dpoqnacv/1/
var regexString = '^'+ $('#searchbox').val().replace("*",".*") + '$';
if(new RegExp(regexString).test('animal'))
$('#resultdiv').html('Matching...');
else
$('#resultdiv').html('Not Matching...');
You can just transform your wildcard into a RegExp and perform your search. Here is a simple example.
var search = document.getElementById("search");
var result = document.getElementById("result");
result.style.color = "red";
function fsearch() {
var str=search.value;
str = str.replace("*", ".*") //Transform your wildcard into a RegExp
result.innerHTML = "animal".match(new RegExp(str));
}
<label for="search">Search : <input name="search" id="search" type="text"/></label>
<input id="ok" type="button" value="ok" onclick="fsearch()"/>
Result : <div id="result"></div>
not bad answers but i think its easier with .test();
var str = "my dog is an animal";
/dog*anim*/.test(str); //returns true
/d*mal/.test(str); //returns true
etc
give it a try

how to replace multiple special character in a number?

I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle

How can I loop through string and replace all periods except the last one?

Let's say I have a string like this:
var test = my.long.file.name.zip
I am getting the total number of periods in this string with javascript like so:
var dots = (test.match(/\./g) || []).length;
I would then like to replace all of the periods in the string with underscores if there is more than one period in the string.
if(dots>"1"){
var newname = test.replace(/\./g, "_");
console.log(newname);
}
The problem is that this is replacing all of the periods. I would like to keep the last on intact. So what I would like the newname variable to read as would be:
my_long_file_name.zip
My guess is that I should use $.each() somehow to iterate over all except the last one to change the name. How should I do this?
You dont necessarily need a loop, you could do it with a more complex regex, which uses a positive lookahead
The regex /\.(?=.*\.)/g finds periods, but only where there is a subsequent period somewhere further along, which means the last one is not matched.
window.onload = function(){
var input = "my.long.file.name.zip"
var result = input.replace(/\.(?=.*\.)/g,'_')
alert(result);
}
Consider splitting the string on '.', then re-joining all but the last with '_':
var test = "my.long.file.name.zip";
parts = test.split('.');
var plen = parts.length;
if (plen > 1) {
test = parts.slice(0, plen - 1).join('_') +
"." +
parts[plen - 1];
}
console.log(test);
a lookahead group in regex will work:
var test = 'my.long.file.name.zip';
var result = test.replace(/\.(?=[^.]*\.)/g, '_');
alert(result);
this matches a dot followed by ('anything but dot' and another dot), replacing only what is outside the group
var test = 'my.long.file.name.zip';
var last_index = test.lastIndexOf('.');
var newname = test;
if (-1 !== last_index) {
newname = test.replace(/\./g, '_');
newname = newname.substring(0, last_index).concat('.', newname.substring(last_index + 1));
}
console.log(newname);

Categories