truncating a string after and before a word in javascript - javascript

How do I truncate a string after or before a pattern?
Say if I have a string "abcdef" I need to truncate everything after "abc" so the output will be:
def
and if i say truncate before "def" the output should be:
abc
Below is the code that I tried
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc"), str1.length);
console.log(str2);
I didn't get the output.
I'm stuck here any help will be much appreciated.

You need to pass length of "abc" as the 2nd argument in substr method
var str1 = "abcdefgh";
var pattern = "abc";
var str2 = str1.substr(str1.indexOf(pattern), pattern.length); <-- check this line
console.log(str2);
However above code might return unexpected results for patterns which are not present in the string.
var str1 = "abcdefgh";
var pattern = "bcd";
var str2 = "";
if(str1.indexOf(pattern)>=0) //if a pattern is not present in the source string indexOf method returns -1
{
//to truncate everything before the pattern
//outputs "efgh"
str2 = str1.substr(str1.indexOf(pattern)+pattern.length, str1.length);
console.log("str2: "+str2);
// if you want to truncate everything after the pattern & pattern itself
//outputs "a"
str3 = str1.substr(0, str1.indexOf(pattern));
console.log("str3: "+str3);
}

var str = "sometextabcdefine";
var pattern = "abc";
var truncateBefore = function (str, pattern) {
return str.slice(str.indexOf(pattern) + pattern.length);
};
var truncateAfter = function (str, pattern) {
return str.slice(0, str.indexOf(pattern));
}
console.log(truncateBefore(str, pattern)); // "define"
console.log(truncateAfter(str, pattern)); // "sometext"

Please see the below code:
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc")+3, str1.length);
alert(str2);
You were correct but one thing you missed is doing +3 in the indexOf.
the indexOf("abc") would return 0 which in turn will give you thw whole string again.
Or check out this fiddle link:
Working Fiddle

How about something like this:
function truncateAfter(original, pattern) {
return original.substring(0, original.indexOf(pattern) + pattern.length);
}
What this does is find the first index of the pattern you're looking for, and return a substring of the original string that starts at the beginning and ends after the first instance of the pattern.
Example Usage:
truncateAfter('dabcdefghi', 'abc');
>> 'dabc'
If instead you want to truncate the output before and after the pattern you're looking for, would just checking if the pattern is in the string and then using the pattern as the output be what you're looking for?
function truncate(original, pattern) {
if (original.indexOf(pattern) != -1) {
return pattern;
}
}
Example Usage:
truncate('dabcdefghi', 'abc');
>> 'abc'

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

Ignore first character of string - JS - Regex

I'm trying to write a Regex that will ignore the first character of a string and start with the second character.
e.g.
str = "14";
test = "4";
This will match ONLY if 4 is is position 2 (end of the string) and NOT at the start, the following will fail
str = "21";
test = "4";
I'm rubbish at Regex and all the options I've tried so far haven't worked.
My current code is like so
filters = filters.replace(/,\s*$/, '');
objRegex = new RegExp('\\/^.{1}(.*)/' + filters, 'gi');
Where filters is a random string consisting of two characters. The current Regex was copied from another SO post but it doesn't work and given my limited knowledge I'm not sure how to make it work, anyone able to help?
Thanks!
I think a Regex is a bit overkill, how about something like this:
var stringToSearch = '14';
var stringToFind = '4';
if (stringToSearch && stringToSearch.length === 2 &&
stringToSearch[1] === stringToFind) {
// do something
}
Just use substring method ?
str = "14";
test = "4";
var str = str.substring(0, 2);
Use following pattern:
"^[\w]{1}4$"

Regex to capture whole word with specific beginning

I need to capture a number passed as appended integers to a CSS class. My regex is pretty weak, what I'm looking to do is pretty simple. I thought that "negative word boundary" \B was the flag I wanted but I guess I was wrong
string = "foo bar-15";
var theInteger = string.replace('/bar\-\B', ''); // expected result = 15
Use a capture group as outlined here:
var str= "foo bar-15";
var regex = /bar-(\d+)/;
var theInteger = str.match(regex) ? str.match(regex)[1] : null;
Then you can just do an if (theInteger) wherever you need to use it
Try this:
var theInteger = string.match(/\d+/g).join('')
string = "foo bar-15";
var theInteger = /bar-(\d+)/.exec(string)[1]
theInteger // = 15
If you just want the digits at the end (a kind of reverse parseInt), why not:
var num = 'foo bar-15'.replace(/.*\D+(\d+)$/,'$1');
or
var m = 'foo bar-15'.match(/\d+$/);
var num = m? m[0] : '';

Regular Expression in JS

How do you trim all of the text after a comma using JS?
I have: string = Doyletown, PA
I want: string = Doyletown
var str = 'Doyletown, PA';
var newstr=str.substring(0,str.indexOf(',')) || str;
I added the || str to handle a scenario where the string has no comma
How about a split:
var string = 'Doyletown, PA';
var parts = string.split(',');
if (parts.length > 0) {
var result = parts[0];
alert(result); // alerts Doyletown
}
using regular expression it will be like:
var str = "Doyletown, PA"
var matches = str.match(/^([^,]+)/);
alert(matches[1]);
jsFiddle
btw: I would also prefer .split() method
Or more generally (getting all the words in a comma separated list):
//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace.
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g);
Try this:
str = str.replace(/,.*/, '');
Or play with this jsfiddle

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);

Categories