I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);
Related
I need to check whether a string contains other than the specified words/sentence (javascript), it will return true if:
it contains an alphabets, except this phrase: ANOTHER CMD
it contains other than specified multiple sequence of numbers for example: ["8809 8805", "8806 8807"] (the numbers are examples I should be able to test the string for any array of numbers)
Thank you!
Yes you can replace all not in the array
const arr = ["ANOTHER CMD","8809 8805", "8809 8805"]
const okContent = str => {
arr.forEach(entry => str = str.replaceAll(entry,""))
return str.trim()==="";
};
console.log(okContent('Has other stuff than ANOTHER CMD and 8809 8805'))
console.log(okContent('8809 8805 ANOTHER CMD 8809 8805'))
I don't know if it's the correct way of doing it but this worked for me:
replace all the valid words with balnk (using replace)
check if the string is left empty
if it's empty, it means that the string does not contain any unwanted string (to check for space you could use trim method)
you can try regex!
use your array of strings as the '|' separated regex value
and check the specified string in the given line. if it presents negate the output.
const regex = /(ANOTHER CMD|8809 8805|8806 8807)/i
console.log(!regex.test('Should not contain word ANOTHER CMD'))
console.log(regex.test('Should contain word ANOTHER CMD'))
How to use the javascript split splice slice methods to convert the:
1.18.0-AAA-1 into 1.18.0.
Start with the initial value, determine that the portion you want is before the first hyphen, so use that as the delimiter for the split. Perform the split and then the first portion will be everything up to but not including that first hyphen. You don't need slice or splice for this - just split. Then just add the dot at the end for the trailing dot.
var x="1.18.0-AAA-1";
var y=x.split("-");//splits it at each "-";
var z=y[0]+".";//gives 1.18.0.
however if you are asking to use each of the threeemethods to yield the outcome, then this sounds like homework and you should try doing it on your own. Best way to learn is to try.
Use split to create an array from your string
var str = "1.18.0-AAA-1";
var parts = str.split("-"); // this returns the array ["1.18.0", "AAA", "1"]
Now the easiest way to get what you want is doing:
parts[0];
In my web page, I have:
var res = number.match(/[0-9\+\-\(\)\s]+/g);
alert(res);
As you can see, I want to get only numbers, the characters +, -, (, ) and the space(\s)
When I tried number = '98+66-97fffg9', the expected result is: 98+66-979
but I get 98+66-97,9
the comma is an odd character here! How can eliminate it?
Its probably because you get two groups that satisfied your expression.
In other words: match mechanism stops aggregating group when it finds first unwanted character -f. Then it skips matching until next proper group that, in this case, contains only one number - 9. This two groups are separated by comma.
Try this:
var number = '98+66-97fffg9';
var res = number.match(/[0-9\+\-\(\)\s]+/g);
// res is an array! You have to join elements!
var joined = res.join('');
alert(joined);
You're getting this because your regex matched two results in the number string, not one. Try printing res, you'll see that you've matched both 98+66-979 as well as 9
String.match returns an array of matched items. In your case you have received two items ['98+66-97','9'], but alert function outputs them as one string '98+66-97,9'. Instead of match function use String.replace function to remove(filter) all unallowable characters from input number:
var number = '98+66-97fffg9',
res = number.replace(/[^0-9\+\-\(\)\s]+/g, "");
console.log(res); // 98+66-979
stringvariable.match(/[0-9\+\-\(\)\s]+/g); will give you output of matching strings from stringvariable excluding unmatching characters.
In your case your string is 98+66-97fffg9 so as per the regular expression it will eliminate "fffg" and will give you array of ["98+66-97","9"].
Its default behavior of match function.
You can simply do res.join('') to get the required output.
Hope it helps you
As per documents from docs, the return value is
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
S,your return value contains
["98+66-97", "9"]
So if you want to skip parentheses-captured matched results
just remove g flag from regular expression.
So,your expression should like this one
number.match(/[0-9\+\-\(\)\s]+/); which gives result ["98+66-97"]
I am trying to fetch the value after equal sign, its works but i am getting duplicated values , any idea whats wrong here?
// Regex for finding a word after "=" sign
var myregexpNew = /=(\S*)/g;
// Regex for finding a word before "=" sign
var mytype = /(\S*)=/g;
//Setting data from Grid Column
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
var newtype = mytype.exec(strNew);
alert(matchNew);
https://jsfiddle.net/6vjjv0hv/
exec returns an array, the first element is the global match, the following ones are the submatches, that's why you get ["=20", "20"] (using console.log here instead of alert would make it clearer what you get).
When looking for submatches and using exec, you're usually interested in the elements starting at index 1.
Regarding the whole parsing, it's obvious there are better solution, like using only one regex with two submatches, but it depends on the real goal.
You can try without using Regex like this:
var val = 'QCById=20';
var myString = val.substr(val.indexOf("=") + 1);
alert(myString);
Presently exec is returning you the matched value.
REGEXP.exec(SOMETHING) returns an array (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec).
The first item in the array is the full match and the rest matches the parenthesized substrings.
You do not get duplicated values, you just get an array of a matched value and the captured text #1.
See RegExp#exec() help:
If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
Just use the [1] index to get the captured text only.
var myregexpNew = /=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
}
To get values on both sides of =, you can use /(\S*)=(\S*)/g regex:
var myregexpNew = /(\S*)=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
console.log(matchNew[2]);
}
Also, you may want to add a check to see if the captured values are not undefined/empty since \S* may capture an empty string. OR use /(\S+)=(\S+)/g regex that requires at least one non-whitespace character to appear before and after the = sign.
I'm trying to find all occurrences of items in HTML page that are in between <nobr> and </nobr> tags.
EDIT:(nobr is an example. I need to find content between random strings, not always tags)
I tried this
var match = /<nobr>(.*?)<\/nobr>/img.exec(document.documentElement.innerHTML);
alert (match);
But it gives only one occurrence. + it appears twice, once with the <nobr></nobr> tags and once without them. I need only the version without the tags.
you need to do it in a loop
var match, re = /<nobr>(.*?)<\/nobr>/img;
while((match = re.exec(document.documentElement.innerHTML)) !== null){
alert(match[1]);
}
use the DOM
var nobrs = document.getElementsByTagName("nobr")
and you can then loop through all nobrs and extract the innerHTML or apply any other action on them.
(Since I can't comment on Rafael's correct answer...)
exec is doing what it is supposed to do - finding the first match, returning the result in the match object, and setting you up for the next exec call. The match object contains (at index 0) the whole of the string matched by the whole of the regex. In subsequent slots are the bits of the string matched by the parenthesized subgroups. So match[1] contains the bit of the string matched by "(.*?)" in your example.
you can use
while (match = /<nobr>(.*?)<\/nobr>/img.exec("foo <nobr> hello </nobr> bar <nobr> world </nobr> foobar"))
alert (match[1]);
If the strings you're using aren't xml elements, and you're sticking with regexes the return value you're getting can be explained by the bracketing. .exec returns the whole matching string followed by the contents of the bracketed expressions.
If your doc contains:
This is out.
Bzz. This is in. unBzz.
then
/Bzz.(.*?)unBzz./img.exec(document.documentElement.innerHTML)
Will give you 'Bzz. This is in. unBzz.' in element 0 of the returned array and 'This is in.' in element 1. Trying to display the whole array gives both as a comma separated list because that's what JavaScript does to try to display it.
So
alert($match[1]);
is what you're after.
it takes to steps but you could do it like this
match = document.documentElement.innerHTML.match(/<nobr>(.*?)<\/nobr>/img)
alert(match)//includes '<nobr>'
match_length = match.length;
for (var i = 0; i < match_length; i++)
{
var match2 = match[i].match(/<nobr>(.*?)<\/nobr>/im);//same regex without the g option
alert(match2[1]);
}