Regex - From PHP to JS
Regex - From PHP to JS
一位用户好心地帮助我在PHP中使用regex,但现在我意识到我也需要在JS中使用它。我花了大量的时间进行测试/试验,但没有成功。
在JS中,我想把这个变成:
[data-user="12345-6789" data-userId="3456-789"]John Smith[/] ...Blablabla some other text... [data-user="4567-891011" data-userId="5678-9101112"]Foo Bar[/]
进入:
<span data-user="12345-6789" data-userId="3456-789">John Smith</span> ...Blablabla some other text... <span data-user="4567-891011" data-userId="5678-9101112">Foo Bar</span>
这是我的PHP正则表达式,它运行得很好:
$regex = '~'[(data-user="['d-]+")'s+(data-userId="['d-]+")']'s*(.+?)'s*'['/']'s*(.*)~is';
while (preg_match($regex, $string)) {
$string = preg_replace($regex, "<span $1 $2>$3</span>$4", trim(strip_tags($string)));
}
附言:我完全知道用正则表达式解析HTML是不受欢迎的,但由于一切都是一致的,我认为这将是最好的方法。
非常感谢。
我简化了RegEx,减少了它的硬编码,允许您在标记中也有其他属性等。
在JavaScript中,您可以只使用String.prototype.replace()
,因为它接受RegEx。
var string = '[data-user="12345-6789" data-userId="3456-789"]John Smith[/] ...Blablabla some other text... [data-user="4567-891011" data-userId="5678-9101112"]Foo Bar[/]'
var regex = /'[([^']]*)']'s*([^'[]*)'s*'['/']/ig;
console.log(string.replace(regex, '<span $1>$2</span>'));
在我看来,逐字逐句地翻译它很好。只需注意正则表达式本身的更改,即将~
更改为/
并删除s
修饰符。
var regex = /'[(data-user="['d-]+")'s+(data-userId="['d-]+")']'s*(.+?)'s*'['/']'s*(.*)/i;
var str = '[data-user="12345-6789" data-userId="3456-789"]John Smith[/] ...Blablabla some other text... [data-user="4567-891011" data-userId="5678-9101112"]Foo Bar[/]';
var html = str;
while (regex.test(html)) {
html = html.replace(regex, '<span $1 $2>$3</span>$4');
}
console.log(html);
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- Node.js - POST to iFrame?
- Php variable obj to js
- FullCalendar backend PHP/JS to symfony 3
- Can't get the tail to wag (animate) in three.js?
- 为什么node.js不等到恢复完成(_search request in to elasticsearch)
- nodemon找不到模块'/路径/to/project/home/index.js'
- HTML to JS Object
- Ruby array to js array in .js.erb file on rails
- PHP to JS:打印与 AJAX responseText 兼容的 js 变量(如 PHP echo)
- Dart to JS:如何调试生成的Javascript错误
- c# class to Js class?
- Regex - From PHP to JS
- MySQLI_ASSOC to JS array
- moment construction falls back to js Date
- 迁移& lt; script>…& lt; / script>To .js文件失败
- Python csv.reader() to JS?
- SignalR点对点(js to js)通信
- XMLHttpRequest to .js file
- Changing from PHP to JS