I have a string like this:
Franciscan St. Francis Health - Indianapolis
I need to extract everything after '-' including the dash itself and output it in the second line..How do I extract everything before '-'?? Regex or jquery?
The string infront of '-' will be dynamic and could have varying number of letters...
Neither. I would just use the native .split() function for strings:
var myString = 'Franciscan St. Francis Health - Indianapolis';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis']
Once you've crated the stringArray variable, you can output the original string's pieces in whatever way you want, for example:
alert('-' + stringArray[1]); //alerts "- Indianapolis"
Edit
To address a commenter's follow-up question: "What if the string after the hyphen has another hyphen in it"?
In that case, you could do something like this:
var myString = 'Franciscan St. Francis Health - Indianapolis - IN';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis ', ' IN']
alert('-' + stringArray.slice(1).join('-')); //alerts "- Indianapolis - IN"
Both .slice() and .join() are native Array methods in JS, and join() is the opposite of the .split() method used earlier.
Regex or jquery?
False dichotomy. Use String.splitMDN
var tokens = 'Franciscan St. Francis Health - Indianapolis'.split('-');
var s = tokens.slice(1).join('-'); // account for '-'s in city name
alert('-' + s);
DEMO
join()MDN
slice()MDN
Probably no need for regex or jquery. This should do it:
var arr = 'Franciscan St. Francis Health - Wilkes-Barre'.split('-');
var firstLine = arr[0]
var secondLine = arr.slice(1).join('-');
Ideally, your data would be stored in two separate fields, so you don't have to worry about splitting strings for display.
Related
I need to get intials only 2 characters after spaces, here is the sample
const string = "John Peter Don";
const result = string.match(/\b(\w)/g).join('');
console.log(result)// JPD->> i want only JP
One regex approach would be to capture all leading capital letters using match(). Then, slice off the first two elements and join together to form a string output.
var string = "John Peter Don";
var initials = string.match(/\b[A-Z]/g).slice(0, 2).join("");
console.log(initials);
Implementing what Wiktor Stribiżew suggested in the comments
const str = "John Peter Don";
let array = str.split(" ");
console.log(array[0][0], array[1][0]);
console.log("In one string: ", array[0][0] + array[1][0]);
I am trying to change specific word in a string with something else. For example, I want to change 'John' in let name = 'Hi, my name is John.'; to 'Jack'.
I know how to split a string by words or characters. I also know how to remove commas, periods, and other symbols in a string. However, if I split the given string with a separator (" "), I will have 'John.' which I do not want. (I know I can switch 'John.' with 'Jack.' but assume that I have an key and value pairs in an object and I am using the values which are names {Father: Jack, Mother: Susan, ...}
I don't know how to separate a string word by word including commas and periods.
For example, if I was given an input which is a string:
'Hi, my name is John.'
I want to split the input as below:
['Hi', ',', 'my', 'name', 'is', 'John', '.']
Does anyone know how to do it?
Below is the challenge I am working on.
Create a function censor that accepts no arguments. censor will return a function that will accept either two strings, or one string. When two strings are given, the returned function will hold onto the two strings as a pair, for future use. When one string is given, the returned function will return the same string, except all instances of a first string (of a saved pair) will be replaced with the second string (of a saved pair).
//Your code here
const changeScene = censor();
changeScene('dogs', 'cats');
changeScene('quick', 'slow');
console.log(changeScene('The quick, brown fox jumps over the lazy dogs.')); // should log: 'The slow, brown fox jumps over the lazy cats.'
I think your real question is "How do I replace a substring with another string?"
Checkout the replace method:
let inputString = "Hi, my name is John.";
let switch1 = ["John", "Jack"];
let switched = inputString.replace(switch1[0], switch1[1]);
console.log(switched); // Hi, my name is Jack.
UPDATE: If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b), you can use RegExp:
let inputString = "I'm John, or johnny, but I prefer john.";
let switch1 = ["John", "Jack"];
let re = new RegExp(`\\b${switch1[0]}\\b`, 'gi');
console.log(inputString.replace(re, switch1[1])); // I'm Jack, or johnny, but I prefer Jack.
You can Try This ...
var string = 'Hi, my name is John.';
//var arr = string.split(/,|\.| /);
var arr = string.split(/([,.\s])/);
console.log(arr);
Using 'Hi, my name is John.'.split(/[,. ]/); will do the job. It will split commas and periods and spaces.
Edit: For those who want to keep the comma and period, here is my wildly inefficient method.
var str = 'Hi, my name is John.'
str = str.replace('.', 'period');
str = str.replace(',', 'comma');
str = str.split(/[,. ]/);
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf('period') > -1) {
str[i] = str[i].replace('period', '');
str.splice(i+1, 0, ".");
} else if (str[i].indexOf('comma') > -1) {
str[i] = str[i].replace('comma', '');
str.splice(i+1, 0, ",");
}
}
console.log(str);
need to filter a collection of strings based on a rather complex query I have query input as a string
var query =ti,su,ab(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)));
The query can change
From this query INPUT string I want to collect just the important words:
the result that I expected = study trail research challeng* n/1design* method* behavior* behaviour* behavior* behaviour* n/1change* modification*
my result= study trail research challeng* design* method*behavior* behaviour* behavior* behaviour*change* modification*
my problem here is sometimes I got two words concatenate as an example method*behavior* and behaviour*change* and that's wrong
DEMO:
This my regexp: delete words from the query: ( ti, ab, su, AND, OR, NEAR/n, P/n, pre/n n/n ), brackets () and the comma ,
/ ?[()]|\b(AND|OR|(NEAR|n|PRE|P)/\d+)(\s|$)|\b(ti|ab|su|,)\b ? /gi
var query = "ti,ab,su(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)))";
var subst= "";
var str = query.replace(/ ?[()]|\b(AND|OR|(NEAR|n|PRE|P)\/\d+)(\s|$)|\b(ti|ab|su|,)\b ?/gi,subst);
console.log(str)
every single word need to be sperate with whitespace.
I'm looking for your suggestion.
Thanks.
Replace your matched things with a space, then condense the space afterwards.
var query = "ti,ab,su(((study OR trail OR research pre/2 challeng*) n/1 (design* AND method*)) (behavior* n/1 behaviour*) OR ((behavior* or behaviour*)n/1 (change* near/6 modification*)))";
var subst= " ";
var str = query.replace(/ ?[()]|\b(AND|OR|(NEAR|n|PRE|P)\/\d+)(\s|$)|\b(ti|ab|su|,)\b ?/gi,subst);
str = str.replace(/^ +|( ) +| +$/g,"$1");
console.log(str)
Take this string as example:
'The strong, fast and gullible cat ran over the street!'
I want to create a function that takes this string and creates the following array:
['The ','strong, ','fast ','and ','gullible ','cat ','ran ','over ','the ','street!']
Observe that I want to keep each puctuation and space after each word.
This regular expression will match what you want: /[^\s]+\s*/g;
EXAPMLE:
var str = 'The strong, fast and gullible cat ran over the street!';
var result = str.match(/[^\s]+\s*/g);
console.log(result);
You can split at word boundaries followed by a word character:
var str = 'The strong, fast and gullible cat ran over the street!';
console.log(str.split(/\b(?=\w)/));
As #Summoner commented (while I was modifying my code to do it), if we add some char(s) that we want to use as a delimiter, we can then split on that, rather than the spaces.
var s= 'The strong, fast and gullible cat ran over the street!';
s = s.replace(/\s+/g, " **");
var ary = s.split("**");
console.log(ary);
Gonna toss my solution into the ring as well. :)
var sTestVal = 'The strong, fast and gullible cat ran over the street!';
var regexPattern = /[^ ]+( |$)/g;
var aResult = sTestVal.match(regexPattern)
console.log(aResult);
The result is:
["The ", "strong, ", "fast ", "and ", "gullible ", "cat ", "ran ", "over ", "the ", "street!"]
The regex pattern breaks down like this:
[^ ]+ - matches one or more non-space characters, and then
( |$) - either a space or the end of the string
g - it will match all instances of the patternthe end
I want to exclude characters from displaying in a vbulletin template.
For example, if a user writes:
"[Hello World] How are you?"
I want to ecxlude "[" and "]" all that's inside so it only displays:
"How are you?"
Is there a way to do this?
Use JavaScript string operations .getIndexOf() and .substring(). Get the position of the first bracket, get the position of the second bracket, split the string into 3 substrings, the middle section being between the two indexed values, and then add just the first and third substrings together. Like this:
var string = "[Hello World] How are you?";
var bracket1 = string.getIndexOf("[");
var bracket2 = string.getIndexOf("]");
var substring1 = string.substring(0,bracket1);
var substring2 = string.substring(bracket1,bracket2);
var substring3 = string.substring(bracket2,string.length);
var solution = substring 1 + " " + substring 3;
At least, that's the concept. Everything may not be right on, but you could futz with the numbers a little to get it perfect.
Or if you don't need to worry about what comes before [], simply use .split():
var string = "[Hello World] How are you?";
var solutionArray = string.split("]");
var solution = solutionArray[1];
Hope this helps!