This question already has answers here:
JavaScript regex pattern concatenate with variable
(3 answers)
Closed 7 years ago.
I have a regex to check if a string contains a specific word. It works as expected:
/\bword\b/.test('a long text with the desired word amongst others'); // true
/\bamong\b/.test('a long text with the desired word amongst others'); // false
But i need the word which is about to be checked in a variable. Using new RegExp does not work properly, it always returns false:
var myString = 'a long text with the desired word amongst others';
var myWord = 'word';
new RegExp('\b' + myWord + '\b').test(myString); // false
myWord = "among";
new RegExp('\b' + myWord + '\b').test(myString); // false
What is wrong here?
var myWord = 'word';
new RegExp('\\b' + myWord + '\\b')
You need to double escape the \ when building a regex from a string.
This is because \ begins an escape sequence in a string literal, so it never makes it to the regex. By doing \\, you're including a literal '\' character in the string, which makes the regex /\bword\b/.
Related
This question already has answers here:
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 years ago.
I have string like this:
var str = "Hello (World) I'm Newbie";
how to get World from string above using RegExp?, I'm sorry I don't understand about regex.
Thank's
Rather than using a regex - use .split()...Note the escaped characters in the splits. The first split gives "World) I'm Newbie" and the second gives "World".
var str = "Hello (World) I'm Newbie";
var strContent = str.split('\(')[1].split('\)')[0];
console.log(strContent); // gives "World"
Assuming that there will be atleast one such word, you can do it using String#match. The following example matches the words between parentheses.
console.log(
"Hello (World) I'm Newbie"
.match(/\(\w+\)/g)
.map(match => match.slice(1, -1))
)
This might help you for your regex
\w match whole world
+ plus with another regex
[] starts group
^ except
(World) matching word
var str = "Hello (World) I'm Newbie";
var exactword=str.replace(/\w+[^(World)]/g,'')
var filtered = str.replace(/(World)/g,'')
alert(exactword)
alert(filtered)
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");
This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 7 years ago.
I'm trying to target the first letter of each word in a string. I'm working in JavaScript. I've found discussions for Python and PHP that don't address my problem specific to JavaScript.
str = "i'm a little tea pot"
regEx = /^.|\b[a-z]/g
I have a function that uppercases each letter the regEx finds. My result is the m after the apostrophe is capitalized. How do I avoid this?
After uppercase function:
I'M A Little Tea Pot"
Capitalize first letter of every word?
var string = prompt("Enter a string");
function capitalizeFirstWord(str) {
return str.split(/\s+/).map(function(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}).join(' ');
}
document.getElementById("capitalized").innerHTML = capitalizeFirstWord(string);
<p id="capitalized"></p>
You split a string at a word boundary. As a parameter you pass in either an empty string or the whitespace character \s. This creates an array of all words in the sentence.
To get the first character, you can use word[0] or word.charAt(0). You then perform string concatenation with the rest of the string.
This gives you an entirely new array, which needs to be converted back to a string. Call the join method on this new array
You may use call-back function in str.replace.
var str = "i'm a little tea pot"
alert(str.replace(/(^|\s)([a-z])/g, function(match, group_1, group_2){return group_1 + group_2.toUpperCase()}))
And also if you want to convert the chars following the first char to lowercase then try this.
str.replace(/(^|\s)([a-z])(\S*)/g, function(x,y, z, a){return y + z.toUpperCase() + a.toLowerCase()})
This question already has an answer here:
Javascript Regular Expression not matching
(1 answer)
Closed 7 years ago.
I'm trying to replace all occurences of {0}, {1}, {2}, etc in a string with Javascript.
Example string:
var str = "Hello, my name is {0} and I'm {1} years.";
I'm tried the following to construct the regexp:
var regex1 = new RegExp("{" + i + "}", "g")
var regex2 = new RegExp("\{" + i + "\}", "g")
Both attempts throws the error:
Invalid regular expression: /{0}/: Nothing to repeat
I use replace like this:
str.replace(regex, "Inserted string");
Found all kinds of StackOverflow posts with different solutions, but not quite to solve my case.
The string literal "\{" results in the string "{". If you need a backslash in there, you need to escape it:
"\\{"
This will results in the regex \{..\}, which is the correct regex syntax.
Having said that, your approach is more than weird. Using a regex you should do something like this:
var substitues = ['foo', 'bar'];
str = str.replace(/\{(\d+)\}/, function (match, num) {
return substitutes[num];
});
In other words, don't dynamically construct a regex for each value; do one regex which matches all values and lets you substitute them as needed.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I trim a string in javascript?
I need to remove only the last and the first spaces from a generic string.
Example:
var str = " hello world "; // become "hello world"
var str = "ehi, do you come from ? "; // become "ehi, do you come from ?"
var str = "I am from Cina"; // remain "I am from Cina"
How can I do that ?
The trim from jQuery is what you are looking for.
$.trim(' string with spaces at the ends ');
Or plain javascript:
' string with spaces at the ends '.trim()