Finding Emojis in Strings - javascript

So I'm trying to find and replace emojis in strings. This is my approach with regexp so far.
const replaceEmojis = function (string) {
String.prototype.regexIndexOf = function (regex, startpos) {
const indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
// generate regexp
let regexp;
try {
regexp = new RegExp('\\p{Emoji}', "gu");
} catch (e) {
//4 firefox <3
regexp = new RegExp(`(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])`, 'g');
}
// get indices of all emojis
function getIndicesOf(searchStr, str) {
let index, indices = [];
function getIndex(startIndex) {
index = str.regexIndexOf(searchStr, startIndex);
if (index === -1) return;
indices.push(index);
getIndex(index + 1)
}
getIndex(0);
return indices;
}
const emojisAt = getIndicesOf(regexp, string);
// replace emojis with SVGs
emojisAt.forEach(index => {
// got nothing here yet
// const unicode = staticHTML.charCodeAt(index); //.toString(16);
})
The problem with this is that I only get an array with indices where the emojis are in the string. But with only these indices I can't replace them because I don't know how many (UTF-16) bytes they take up.
Also for replacing them I need to know what emoji it is I am replacing.
So, is there a way to also get the length of the emoji? Or is there a better (perhaps simpler) way than mine to replace emojis?

Alright, so turns out I just had a little bit of a mental block.
To find the emojis I don't need to get the indices as WolverinDEV mentioned. Although just using string.replace with /\p{Emoji}/gu does't work as this breaks up e.g. 🙋🏻‍♂️ into 🙋,🏻, and ♂. So I tweaked the regexp to account for that: /[\p{Emoji}\u200d]+/gu. Now the emoji is returned in full because zero width joiner are included.
This is what I got (if anyone cares):
const replaceEmojis = function (string) {
const emojis = string.match(/[\p{Emoji}\u200d]+/gu);
// console.log(emojis);
// replace emojis with SVGs
emojis.forEach(emoji => {
// get the unicodes of the emoji
let unicode = "";
function getNextChar(pointer) {
const subUnicode = emoji.codePointAt(pointer);
if (!subUnicode) return;
unicode += '-' + subUnicode.toString(16);
getNextChar(++pointer);
}
getNextChar(0);
unicode = unicode.substr(1); // remove the beginning dash '-'
console.log(unicode.toUpperCase());
// replace emoji here
// string = string.replace(emoji, `<svg src='path/to/svg/${unicode}.svg'>`)
})
return string;
}
This still needs work, e.g. as there are Low Surrogates in the outputted unicode, but fundamentally, this works.
EDIT:
First improvement:
You may don't need this but to get rid of low surrogate characters add a condition in getNextChar()
if (!(subUnicode >= 56320 && subUnicode <= 57343)) unicode += '-' + subUnicode.toString(16);
This only adds the character code if it isn't a low surrogate character.
Second improvement:
Add the variation selector 16 (U+FE0F) to the regexp to select more emojis en bloc:
/[\p{Emoji}\u200d\ufe0f]+/gu

Well you've already a working RegExp so you could use String.replace:
string.replace(regexp, my_emojy => {
return "<an emoji was here>";
});
So you've no need at all to find any indices.

Related

JavaScript remove a character from a string and remove the previous character

How do I remove a character from a string and remove the previous character as well?
Example:
"ABCXDEXFGHXIJK"
I want to split the string by "X" and remove the previous character which returns
"ABDFGIJK" // CX, EX, HX are removed
I found this thread but it removes everything before rather than a specific amount of characters: How to remove part of a string before a ":" in javascript?
I can run a for loop but I was wondering if there was a better/simpler way to achieve this
const remove = function(str){
for(let i = 0; i < str.length; i++){
if(str[i] === "X") str = str.slice(0, i - 1) + str.slice(i + 1);
}
return str
}
console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK
You can use String.prototype.replace and regex.
"ABCXDEXFGHXIJK".replace(/.X/g, '')
The g at the end is to replace every occurrence of .X. You can use replaceAll as well, but it has less support.
"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')
If you want it to be case insensitive, use the i flag as well.
"ABCXDEXFGHXIJK".replace(/.x/gi, '')
The simplest way is to use a regular expression inside replace.
"ABCXDEXFGHXIJK".replace(/.X/g, "")
.X means "match the combination of X and any single character before it, g flag after the expression body repeats the process globally (instead of doing it once).
While not the most computationally efficient, you could use the following one-liner that may meet your definition of "a better/simpler way to achieve this":
const remove = str => str.split("X").map((ele, idx) => idx !== str.split("X").length - 1 ? ele.slice(0, ele.length - 1) : ele).join("");
console.log(remove("ABCXDEXFGHXIJK"));
Maybe you can use recursion.
function removeChar(str, char){
const index = str.indexOf(char);
if(index < 0) return str;
// removes 2 characters from string
return removeChar(str.split('').splice(index - 2, index).join());
}
Try this way (Descriptive comments are added in the below code snippet itself) :
// Input string
const str = "ABCXDEXFGHXIJK";
// split the input string based on 'X' and then remove the last item from each element by using String.slice() method.
const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1));
// Output by joining the modified array elements.
console.log(splittedStr.join(''))
By using RegEx :
// Input string
const str = "ABCXDEXFGHXIJK";
// Replace the input string by matching the 'X' and one character before that with an empty string.
const modifiedStr = str.replace(/.X/g, "")
// Output
console.log(modifiedStr)

Find letters in random string exactly, using RegEx

The emphasis here is on the word exactly. This needs to work for any number of permutations, so hopefully my example is clear enough.
Given a string of random letters, is it possible (using RegEx) to match an exact number of letters within the given string?
So if I have a string (str1) containing letters ABZBABJDCDAZ and I wanted to match the letters JDBBAA (str2), my function should return true because str1 contains all the right letters enough times. If however str1 were to be changed to ABAJDCDA, then the function would return false as str2 requires that str1 have at least 2 instances of the letter B.
This is what I have so far using a range:
const findLetters = (str1, str2) => {
const regex = new RegExp(`[${str2}]`, 'g')
const result = (str1.match(regex))
console.log(result)
}
findLetters('ABZBABJDCDAZ', 'JDBBAA')
As you can see it matches the right letters, but it matches all instances of them. Is there any way to do what I'm trying to do using RegEx? The reason I'm focusing on RegEx here is because I need this code to be highly optimised, and so far my other functions using Array.every() and indexOf() are just too slow.
Note: My function only requires to return a true/false value.
Try (here we sort letters of both strings and then create regexp like A.*A.*B.*B.*D.*J)
const findLetters = (str1, str2) => {
const regex = new RegExp([...str2].sort().join`.*`)
return regex.test([...str1].sort().join``)
}
console.log( findLetters('ABZBABJDCDAZ', 'JDBBAA') );
console.log( findLetters('ABAJDCDA', 'JDBBAA') );
I dont know if regex is the right way for this as this can also get very expensive. Regex is fast, but not always the fastest.
const findLetters2 = (strSearchIn, strSearchFor) => {
var strSearchInSorted = strSearchIn.split('').sort(function(a, b) {
return a.localeCompare(b);
});
var strSearchForSorted = strSearchFor.split('').sort(function(a, b) {
return a.localeCompare(b);
});
return hasAllChars(strSearchInSorted, strSearchForSorted);
}
const hasAllChars = (searchInCharList, searchCharList) => {
var counter = 0;
for (i = 0; i < searchCharList.length; i++) {
var found = false;
for (counter; counter < searchInCharList.length;) {
counter++;
if (searchCharList[i] == searchInCharList[counter - 1]) {
found = true;
break;
}
}
if (found == false) return false;
}
return true;
}
// No-Regex solution
console.log('true: ' + findLetters2('abcABC', 'abcABC'));
console.log('true: ' + findLetters2('abcABC', 'acbACB'));
console.log('true: ' + findLetters2('abcABCx', 'acbACB'));
console.log('false: ' + findLetters2('abcABC', 'acbACBx'));
console.log('true: ' + findLetters2('ahfffmbbbertwcAtzrBCasdf', 'acbACB'));
console.log('false: ' + findLetters2('abcABC', 'acbAACB'));
Feel free to test it's speed and to optimize it as I'm no js expert. This solution should iterate each string once after sorting. Sorting is thanks to https://stackoverflow.com/a/51169/9338645.

Split and replace text by two rules (regex)

I trying to split text by two rules:
Split by whitespace
Split words greater than 5 symbols into two separate words like (aaaaawww into aaaaa- and www)
I create regex that can detect this rules (https://regex101.com/r/fyskB3/2) but can't understand how to make both rules work in (text.split(/REGEX/)
Currently regex - (([\s]+)|(\w{5})(?=\w))
For example initial text is hello i am markopollo and result should look like ['hello', 'i', 'am', 'marko-', 'pollo']
It would probably be easier to use .match: match up to 5 characters that aren't whitespace:
const str = 'wqerweirj ioqwejr qiwejrio jqoiwejr qwer qwer';
console.log(
str.match(/[^ ]{1,5}/g)
)
My approach would be to process the string before splitting (I'm a big fan of RegEx):
1- Search and replace all the 5 consecutive non-last characters with \1-.
The pattern (\w{5}\B) will do the trick, \w{5} will match 5 exact characters and \B will match only if the last character is not the ending character of the word.
2- Split the string by spaces.
var text = "hello123467891234 i am markopollo";
var regex = /(\w{5}\B)/g;
var processedText = text.replace(regex, "$1- ");
var result = processedText.split(" ");
console.log(result)
Hope it helps!
Something like this should work:
const str = "hello i am markopollo";
const words = str.split(/\s+/);
const CHUNK_SIZE=5;
const out = [];
for(const word of words) {
if(word.length > CHUNK_SIZE) {
let chunks = chunkSubstr(word,CHUNK_SIZE);
let last = chunks.pop();
out.push(...chunks.map(c => c + '-'),last);
} else {
out.push(word);
}
}
console.log(out);
// credit: https://stackoverflow.com/a/29202760/65387
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
i.e., first split the string into words on spaces, and then find words longer than 5 chars and 'chunk' them. I popped off the last chunk to avoid adding a - to it, but there might be a more efficient way if you patch chunkSubstr instead.
regex.split doesn't work so well because it will basically remove those items from the output. In your case, it appears you want to strip the whitespace but keep the words, so splitting on both won't work.
Uses the regex expression of #CertainPerformance = [^\s]{1,5}, then apply regex.exec, finally loop all matches to reach the goal.
Like below demo:
const str = 'wqerweirj ioqwejr qiwejrio jqoiwejr qwer qwer'
let regex1 = RegExp('[^ ]{1,5}', 'g')
function customSplit(targetString, regexExpress) {
let result = []
let matchItem = null
while ((matchItem = regexExpress.exec(targetString)) !== null) {
result.push(
matchItem[0] + (
matchItem[0].length === 5 && targetString[regexExpress.lastIndex] && targetString[regexExpress.lastIndex] !== ' '
? '-' : '')
)
}
return result
}
console.log(customSplit(str, regex1))
console.log(customSplit('hello i am markopollo', regex1))

split string only on first instance of specified character

In my code I split a string based on _ and grab the second item in the array.
var element = $(this).attr('class');
var field = element.split('_')[1];
Takes good_luck and provides me with luck. Works great!
But, now I have a class that looks like good_luck_buddy. How do I get my javascript to ignore the second _ and give me luck_buddy?
I found this var field = element.split(new char [] {'_'}, 2); in a c# stackoverflow answer but it doesn't work. I tried it over at jsFiddle...
Use capturing parentheses:
'good_luck_buddy'.split(/_(.*)/s)
['good', 'luck_buddy', ''] // ignore the third element
They are defined as
If separator contains capturing parentheses, matched results are returned in the array.
So in this case we want to split at _.* (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).
In this example our separator (matching _(.*)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .*) would've not been included in the result array as it is the case with simple split that separators are not included in the result.
We use the s regex flag to make . match on newline (\n) characters as well, otherwise it would only split to the first newline.
What do you need regular expressions and arrays for?
myString = myString.substring(myString.indexOf('_')+1)
var myString= "hello_there_how_are_you"
myString = myString.substring(myString.indexOf('_')+1)
console.log(myString)
I avoid RegExp at all costs. Here is another thing you can do:
"good_luck_buddy".split('_').slice(1).join('_')
With help of destructuring assignment it can be more readable:
let [first, ...rest] = "good_luck_buddy".split('_')
rest = rest.join('_')
A simple ES6 way to get both the first key and remaining parts in a string would be:
const [key, ...rest] = "good_luck_buddy".split('_')
const value = rest.join('_')
console.log(key, value) // good, luck_buddy
Nowadays String.prototype.split does indeed allow you to limit the number of splits.
str.split([separator[, limit]])
...
limit Optional
A non-negative integer limiting the number of splits. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.
The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
If limit is 0, no splitting is performed.
caveat
It might not work the way you expect. I was hoping it would just ignore the rest of the delimiters, but instead, when it reaches the limit, it splits the remaining string again, omitting the part after the split from the return results.
let str = 'A_B_C_D_E'
const limit_2 = str.split('_', 2)
limit_2
(2) ["A", "B"]
const limit_3 = str.split('_', 3)
limit_3
(3) ["A", "B", "C"]
I was hoping for:
let str = 'A_B_C_D_E'
const limit_2 = str.split('_', 2)
limit_2
(2) ["A", "B_C_D_E"]
const limit_3 = str.split('_', 3)
limit_3
(3) ["A", "B", "C_D_E"]
This solution worked for me
var str = "good_luck_buddy";
var index = str.indexOf('_');
var arr = [str.slice(0, index), str.slice(index + 1)];
//arr[0] = "good"
//arr[1] = "luck_buddy"
OR
var str = "good_luck_buddy";
var index = str.indexOf('_');
var [first, second] = [str.slice(0, index), str.slice(index + 1)];
//first = "good"
//second = "luck_buddy"
You can use the regular expression like:
var arr = element.split(/_(.*)/)
You can use the second parameter which specifies the limit of the split.
i.e:
var field = element.split('_', 1)[1];
Replace the first instance with a unique placeholder then split from there.
"good_luck_buddy".replace(/\_/,'&').split('&')
["good","luck_buddy"]
This is more useful when both sides of the split are needed.
I need the two parts of string, so, regex lookbehind help me with this.
const full_name = 'Maria do Bairro';
const [first_name, last_name] = full_name.split(/(?<=^[^ ]+) /);
console.log(first_name);
console.log(last_name);
Non-regex solution
I ran some benchmarks, and this solution won hugely:1
str.slice(str.indexOf(delim) + delim.length)
// as function
function gobbleStart(str, delim) {
return str.slice(str.indexOf(delim) + delim.length);
}
// as polyfill
String.prototype.gobbleStart = function(delim) {
return this.slice(this.indexOf(delim) + delim.length);
};
Performance comparison with other solutions
The only close contender was the same line of code, except using substr instead of slice.
Other solutions I tried involving split or RegExps took a big performance hit and were about 2 orders of magnitude slower. Using join on the results of split, of course, adds an additional performance penalty.
Why are they slower? Any time a new object or array has to be created, JS has to request a chunk of memory from the OS. This process is very slow.
Here are some general guidelines, in case you are chasing benchmarks:
New dynamic memory allocations for objects {} or arrays [] (like the one that split creates) will cost a lot in performance.
RegExp searches are more complicated and therefore slower than string searches.
If you already have an array, destructuring arrays is about as fast as explicitly indexing them, and looks awesome.
Removing beyond the first instance
Here's a solution that will slice up to and including the nth instance. It's not quite as fast, but on the OP's question, gobble(element, '_', 1) is still >2x faster than a RegExp or split solution and can do more:
/*
`gobble`, given a positive, non-zero `limit`, deletes
characters from the beginning of `haystack` until `needle` has
been encountered and deleted `limit` times or no more instances
of `needle` exist; then it returns what remains. If `limit` is
zero or negative, delete from the beginning only until `-(limit)`
occurrences or less of `needle` remain.
*/
function gobble(haystack, needle, limit = 0) {
let remain = limit;
if (limit <= 0) { // set remain to count of delim - num to leave
let i = 0;
while (i < haystack.length) {
const found = haystack.indexOf(needle, i);
if (found === -1) {
break;
}
remain++;
i = found + needle.length;
}
}
let i = 0;
while (remain > 0) {
const found = haystack.indexOf(needle, i);
if (found === -1) {
break;
}
remain--;
i = found + needle.length;
}
return haystack.slice(i);
}
With the above definition, gobble('path/to/file.txt', '/') would give the name of the file, and gobble('prefix_category_item', '_', 1) would remove the prefix like the first solution in this answer.
Tests were run in Chrome 70.0.3538.110 on macOSX 10.14.
Use the string replace() method with a regex:
var result = "good_luck_buddy".replace(/.*?_/, "");
console.log(result);
This regex matches 0 or more characters before the first _, and the _ itself. The match is then replaced by an empty string.
Javascript's String.split unfortunately has no way of limiting the actual number of splits. It has a second argument that specifies how many of the actual split items are returned, which isn't useful in your case. The solution would be to split the string, shift the first item off, then rejoin the remaining items::
var element = $(this).attr('class');
var parts = element.split('_');
parts.shift(); // removes the first item from the array
var field = parts.join('_');
Here's one RegExp that does the trick.
'good_luck_buddy' . split(/^.*?_/)[1]
First it forces the match to start from the
start with the '^'. Then it matches any number
of characters which are not '_', in other words
all characters before the first '_'.
The '?' means a minimal number of chars
that make the whole pattern match are
matched by the '.*?' because it is followed
by '_', which is then included in the match
as its last character.
Therefore this split() uses such a matching
part as its 'splitter' and removes it from
the results. So it removes everything
up till and including the first '_' and
gives you the rest as the 2nd element of
the result. The first element is "" representing
the part before the matched part. It is
"" because the match starts from the beginning.
There are other RegExps that work as
well like /_(.*)/ given by Chandu
in a previous answer.
The /^.*?_/ has the benefit that you
can understand what it does without
having to know about the special role
capturing groups play with replace().
if you are looking for a more modern way of doing this:
let raw = "good_luck_buddy"
raw.split("_")
.filter((part, index) => index !== 0)
.join("_")
Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.
So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:
String.prototype.splitOnce = function(regex)
{
var match = this.match(regex);
if(match)
{
var match_i = this.indexOf(match[0]);
return [this.substring(0, match_i),
this.substring(match_i + match[0].length)];
}
else
{ return [this, ""]; }
}
var str = "something/////another thing///again";
alert(str.splitOnce(/\/+/)[1]);
For beginner like me who are not used to Regular Expression, this workaround solution worked:
var field = "Good_Luck_Buddy";
var newString = field.slice( field.indexOf("_")+1 );
slice() method extracts a part of a string and returns a new string and indexOf() method returns the position of the first found occurrence of a specified value in a string.
This should be quite fast
function splitOnFirst (str, sep) {
const index = str.indexOf(sep);
return index < 0 ? [str] : [str.slice(0, index), str.slice(index + sep.length)];
}
console.log(splitOnFirst('good_luck', '_')[1])
console.log(splitOnFirst('good_luck_buddy', '_')[1])
This worked for me on Chrome + FF:
"foo=bar=beer".split(/^[^=]+=/)[1] // "bar=beer"
"foo==".split(/^[^=]+=/)[1] // "="
"foo=".split(/^[^=]+=/)[1] // ""
"foo".split(/^[^=]+=/)[1] // undefined
If you also need the key try this:
"foo=bar=beer".split(/^([^=]+)=/) // Array [ "", "foo", "bar=beer" ]
"foo==".split(/^([^=]+)=/) // [ "", "foo", "=" ]
"foo=".split(/^([^=]+)=/) // [ "", "foo", "" ]
"foo".split(/^([^=]+)=/) // [ "foo" ]
//[0] = ignored (holds the string when there's no =, empty otherwise)
//[1] = hold the key (if any)
//[2] = hold the value (if any)
a simple es6 one statement solution to get the first key and remaining parts
let raw = 'good_luck_buddy'
raw.split('_')
.reduce((p, c, i) => i === 0 ? [c] : [p[0], [...p.slice(1), c].join('_')], [])
You could also use non-greedy match, it's just a single, simple line:
a = "good_luck_buddy"
const [,g,b] = a.match(/(.*?)_(.*)/)
console.log(g,"and also",b)

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