Getting the last substring value of a string with hyphens in it - javascript

I need your help,
How can I get the last value (sub-string) of a text string that has hyphens in it?
var instr = "OTHER-REQUEST-ALPHA"
...some processing here to get the outstr value
var outstr = "ALPHA"

Use String#split and Array#pop methods.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.split('-').pop()
)
Or use String#lastIndexOf and String#substr methods
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.substr(instr.lastIndexOf('-') + 1)
)
Or using String#match method.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.match(/[^-]*$/)[0]
)

The simplest approach is to simply split the string by your delimeter (ie. -) and get the last segment:
var inString = "OTHER-REQUEST-ALPHA"
var outString = inString.split("-").slice(-1)[0]
That's it!

Use SPLIT and POP
"String - MONKEY".split('-').pop().trim(); // "MONKEY"
Or This
string2 = str.substring(str.lastIndexOf("-"))

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);

how to remove array String substring() Method using javascript?

I would like to know how can I remove the First word in the string using JavaScript?
For example, the string is "mod1"
I want to remove mod..I need to display 1
var $checked = $('.dd-list').find('.ModuleUserViews:checked');
var modulesIDS = [];
$checked.each(function (index) { modulesIDS.push($(this).attr("id")); })
You can just use the substring method. The following will give the last character of the string.
var id = "mod1"
var result = id.substring(id.length - 1, id.length);
console.log(result)
Try this.
var arr = ["mod1"];
var replaced= $.map( arr, function( a ) {
return a.replace("mod", "");
});
console.log(replaced);
If you want to remove all letters and keep only the numbers in the string, you can use a regex match.
var str = "mod125lol";
var nums = str.match(/\d/g).join('');
console.log(nums);
// "125"
If you don't want to split the string (faster, less memory consumed), you can use indexOf() with substr():
var id = "mod1"
var result = id.substr(id.indexOf(" ") -0);
console.log(result)

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

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...

How do I use regular expression to get a list of words in an Arabic string?

I have arabi text like these:
احوال العدد، فی اللغة، العربیة
and I want to parse text(without ، and remove space) from them, so I get
'احوال العدد' 'فی اللغة' 'العربیة'
Example:
var m = 'احوال العدد، فی اللغة، العربیة'
m.match(?);
Can someone help me with correct regex for that situation?
Use .split if you want to split a string, not .match.
>>> var m = 'احوال العدد، فی اللغة، العربیة';
>>> res = m.split(/،\s*/)
["احوال العدد", "فی اللغة", "العربیة"]
>>> res[0]
"احوال العدد"
I don't use regex unless I have to. Other options are usually faster for simple cases.
For example, if you just want to split on instances of a single character, try string.split instead of a regex:
var matches = m.split(" ");
You said:
... after ، ...
Not sure what you mean by "after ،".
Just remove it too?
If you just want to remove it too, string.split can still handle that:
var matches = m.split("، "); // Note that it seems to need LTR ordering...
The output you get looks like what you said you are expecting in your question:
'احوال العدد'
'فی اللغة'
'العربیة'
Return matches only after that character is found?
If you want to only return matches that are found after that character first occurs, I'd use string.indexOf and string.substring.
Here's some code that could achieve this (and demo - http://jsfiddle.net/U5Fz7/):
var m = 'احوال العدد، فی اللغة، العربیة'
var matchStartIndex = m.indexOf("،") + 1;
var matches = matchStartIndex > 0 && matchStartIndex < m.length
? m.substring(matchStartIndex).split(" ")
: new Array();
for(var i = 0; i < matches.length; ++i) {
document.write(matches[i] + "<br/>");
}
The extra code here is for error handling, in case ، isn't found, or there are no characters after it.
The output you get is a little weird (the first string is empty), as the string ends up starting with a " ":
''
'فی'
'اللغة،'
'العربیة'
I hope this could help you to erase ",":
var m = 'احوال العدد, فی اللغة, العربیة';
var strReplaceAll = m;
var intIndexOfMatch = strReplaceAll.indexOf( "," );
// Loop over the string value replacing out each matching
// substring.
while (intIndexOfMatch != -1){
// Relace out the current instance.
strReplaceAll = strReplaceAll.replace( ',',' ' )
// Get the index of any next matching substring.
intIndexOfMatch = strReplaceAll.indexOf( "," );
}
//print out the result
document.write(strReplaceAll);
the result could notice here:
احوال العدد فی اللغة العربیة
Without regex :
var str = 'احوال العدد، فی اللغة، العربیة';
var arr = str.split('،');
arr = $.map(arr, function(val, i) {
return val.trim();
});
With RegExp:
x=m.match(/([\u0600-\u060B\u060D-\u06FF][\u0600-\u060B\u060D-\u06FF\s]+[\u0600-\u060B\u060D-\u06FF])/g);
Fiddle: http://jsfiddle.net/doktormolle/WpM4x/

Problem getting substring in jquery

I have a string variable having data
4096;jpg,bmp
or
2048;flv,mpg
I want to split this string into two string in jquery on the basis of ;
You can use JavaScript's split function.
var some_text = "blah;blah;blahness";
var arr = some_text.split(';');
alert(arr[2]); //blahness
here is some code..
var str = '4096;jpg,bmp';
var elements = str.split(';');
alert( elements[0] ); // 4096
alert( elements[1] ); // jpg,bmp

Categories